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='&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;