繁体   English   中英

在传单矩形内添加文本

[英]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组件中。

用HTML创建DivIcon

DivIcon是可以包含HTML而不是图像的图标。 我们将导入Leaflet库,并使用所需的文本创建一个DivIcon

import L from 'leaflet';

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

将DivIcon添加到标记

创建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

将标记添加到地图

最后,我们将PolygonMarkerDivIconMap

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM