[英]Add text inside leaflet rectangle
我正在使用以下代码在leaflet
地图中创建一个矩形。
const rectangles = [[51.49, -0.08], [51.5, -0.06]]
<Rectangle key={key} bounds={rectangle} color="green">
</Rectangle>
我想在矩形内添加文本,例如矩形的标签,有没有办法做到这一点?
我正在为此使用react-leaflet库。
请参考以下代码,此代码使用其中带有工具提示的矩形
{} zoneLabel
<Rectangle key={key} bounds={coordinates}> </Rectangle>
要在地图上书写,我们可以使用Leaflet库中的DivIcon添加到React-Leaflet Marker组件中。
DivIcon
是可以包含HTML而不是图像的图标。 我们将导入Leaflet
库,并使用所需的文本创建一个DivIcon
。
import L from 'leaflet';
const text = L.divIcon({html: 'Your HTML text here'});
创建DivIcon
,我们将其添加到放置在Polygon
中心的Marker中。
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
最后,我们将Polygon
, Marker
和DivIcon
到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='&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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.