Add text inside leaflet rectangle

五迷三道 提交于 2020-02-24 12:36:27

问题


I'm using the following code to create a rectangle in the leaflet map.

const rectangles = [[51.49, -0.08], [51.5, -0.06]]   

<Rectangle key={key} bounds={rectangle} color="green">

</Rectangle>

I want to add a text inside the rectangle like a label for the rectangle is there a way to do this?

I'm using react-leaflet library for this.


回答1:


To write on the map, we can use a DivIcon from the Leaflet library added to a React-Leaflet Marker component.

Create a DivIcon with HTML

A DivIcon is an icon that can contain HTML instead of an image. We'll import the Leaflet library and create a DivIcon with our desired text.

import L from 'leaflet';

const text = L.divIcon({html: 'Your HTML text here'});

Add the DivIcon to a Marker

With the DivIcon created, we'll add it to a Marker placed in the center of a Polygon.

import React from 'react';
import L from 'leaflet';
import { Marker, Polygon } from 'react-leaflet';

const PolygonWithText = props => {
  const center = L.polygon(props.coord).getBounds().getCenter();
  const text = L.divIcon({html: props.text});

  return(
    <Polygon color="blue" positions={props.coords}>
      <Marker position={center} icon={text} />
    </Polygon>
  );
}

export default PolygonWithText

Add the Marker to the Map

Finally, we add the Polygon, Marker, and DivIcon to a Map.

import React, { Component } from 'react';
import {Map, TileLayer} from 'react-leaflet';
import PolygonWithText from './PolygonWithText';

class MyMap extends Component {
  render () {
    return (
      <Map center={[20.75, -156.45]} zoom={13}>
        <TileLayer
          attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
        <PolygonWithText text="MyText" coords={[...]} />
      </Map>
  }
}

export default MyMap;




回答2:


refer the below code, this one uses a rectangle with a tooltip inside it

{zoneLabel}

<Rectangle key={key} bounds={coordinates}>
</Rectangle>



来源:https://stackoverflow.com/questions/50856182/add-text-inside-leaflet-rectangle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!