簡體   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