在传单矩形内添加文本

koh*_*hli 5 leaflet reactjs react-leaflet

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

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

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

</Rectangle>
Run Code Online (Sandbox Code Playgroud)

我想在矩形内添加文本,就像矩形的标签一样,有办法做到这一点吗?

我为此使用了react-leaflet库。

Jas*_*son 8

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

使用 HTML 创建 DivIcon

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

import L from 'leaflet';

const text = L.divIcon({html: 'Your HTML text here'});
Run Code Online (Sandbox Code Playgroud)

将 DivIcon 添加到标记

创建完成后DivIcon,我们将其添加到放置在Polygon.

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

const PolygonWithText = props => {
  const center = L.polygon(props.coords).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
Run Code Online (Sandbox Code Playgroud)

将标记添加到地图

最后,我们将PolygonMarker、 和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='&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;

Run Code Online (Sandbox Code Playgroud)


小智 0

参考下面的代码,这个代码使用一个矩形,里面有一个工具提示

{区域标签}

<Rectangle key={key} bounds={coordinates}>
</Rectangle>
Run Code Online (Sandbox Code Playgroud)