首页 > 解决方案 > 在传单矩形内添加文本

问题描述

我正在使用以下代码在leaflet地图中创建一个矩形。

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

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

</Rectangle>

我想在矩形内添加一个文本,比如矩形的标签有没有办法做到这一点?

我正在为此使用react-leaflet库。

标签: reactjsleafletreact-leaflet

解决方案


要在地图上书写,我们可以使用Leaflet 库中添加到 React-Leaflet Marker组件的DivIcon 。

使用 HTML 创建一个 DivIcon

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

import L from 'leaflet';

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

将 DivIcon 添加到标记

DivIcon创建完成后,我们将其添加到放置在 a 中心的 Marker中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

将标记添加到地图

最后,我们将PolygonMarkerDivIcon加到 aMap中。

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;


推荐阅读