Add text inside leaflet rectangle
Asked Answered
S

2

5

I'm using the following code to create a rectangle in the leaflet map.

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

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

</Rectangle>

I want to add a text inside the rectangle like a label for the rectangle is there a way to do this?

I'm using react-leaflet library for this.

Soave answered 14/6, 2018 at 11:11 Comment(2)
What module/library are you using? Could you please add more info to your question? Are you using some react wrapper for leaflet ?X
@agent_hunt I have added the library i'm usingSoave
F
9

To write on the map, we can use a DivIcon from the Leaflet library added to a React-Leaflet Marker component.

Create a DivIcon with HTML

A DivIcon is an icon that can contain HTML instead of an image. We'll import the Leaflet library and create a DivIcon with our desired text.

import L from 'leaflet';

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

Add the DivIcon to a Marker

With the DivIcon created, we'll add it to a Marker placed in the center of a 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

Add the Marker to the Map

Finally, we add the Polygon, Marker, and DivIcon to a 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;

Fineberg answered 22/3, 2019 at 20:53 Comment(0)
W
0

refer the below code, this one uses a rectangle with a tooltip inside it

{zoneLabel}

<Rectangle key={key} bounds={coordinates}>
</Rectangle>

Whitehall answered 26/7, 2018 at 8:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.