Drawing on Maps in React using leaflet

Abhishek Tripathi
3 min readJun 2, 2020

--

Read the previous story on how to get started with Maps in React

Assumptions

  • The react app is already running.
  • Leaflet-react library is installed.

Draw a Circle

  • Import the ‘Circle’ component from the ‘react-leaflet’
import {Map,TileLayer,Circle} from 'react-leaflet'
  • Define the circle centre and radius ( can use a local or state variable)
constructor(props) {
super(props);
this.state ={
lat : 28.63196,
lng : 77.22054,
zoom : 16,
center : [28.63196, 77.22054],// Any lat long u want as centre
radius : 200
}
}
  • Add Centre Component within the Map component
<Circle center={this.state.center} fillColor="blue" radius={this.state.radius} />
  • Save the files (Start/Restart the application)

Draw a Polygon

  • Define polygon co ordinates (triangle 3, quadrilateral 4 and so on)
const polygon = [
[28.63196, 77.22054],
[28.63196, 75.25054],
[28.13196, 76.28054],
]
  • Import Polygon from the ‘react-leaflet’ file.
import {Map,TileLayer,Circle,Polygon} from 'react-leaflet'
  • Add polygon component layer to the Map Component layer
<Polygon color="purple" positions={polygon} />
  • Save and Restart

Add a Marker & Pop Up

  • Import Marker and Popup Component from react-leaflet
import {Marker, Popup } from 'react-leaflet'
  • Define a position for pop up to appear
  • Add Marker and Popup component within the map
<Marker position={position}>
<Popup>
Hello User
</Popup>
</Marker>
  • Save and Restart:
  • Click on the pop up

Final Code in BasicMap.js

import React,{Component} from 'react';
import {Map,TileLayer,Circle,Polygon} from 'react-leaflet'
import './Basicmaps.css';
import {Marker, Popup } from 'react-leaflet'
const polygon = [
[28.63196, 77.22054],
[28.63196, 75.25054],
[28.13196, 76.28054],
]
class Basicmaps extends Component {
constructor(props) {
super(props);
this.state ={
lat : 28.63196,
lng : 77.22054,
zoom : 8,
center : [28.63196, 77.22054], // Any lat long u want as centre
radius : 200
}
}
render() {
const position = [this.state.lat,this.state.lng];
return <React.Fragment>
<h1>Hello, Component Maps</h1>
<Map center={position} zoom={this.state.zoom}>
<TileLayer
attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Circle center={this.state.center} fillColor="blue" radius={this.state.radius} />
<Polygon color="purple" positions={polygon} />
<Marker position={position}>
<Popup>
Hello User
</Popup>
</Marker>
</Map>
</React.Fragment>;

}
}
export default Basicmaps

You can draw various shapes add other features, please follow the official leaflet documentation for more:

If you want help with any feature please drop a message will try to show the code.

Thanks

--

--