Drawing Border / Polygon on Map Using React Leaflet

Drawing Border / Polygon on Map Using React Leaflet

So i have actually known leaflet for quite a while, but in the past i used to implement it using vanilla JS, now i almost do any front end stuff using React, so i need to learn how to use leaflet in React. As you may already know, leaflet is kind of really complex and has lots of APIs, so it must be quite difficult to port leaflet to React.

Lucky for us, the React community is growing so fast, i believe any top open source Javascript project has already been ported to React, maybe porting to React from vanilla is not something that difficult so people can do it pretty easily, but I don't know, i have never done that.

I use this react-leaflet library, basically just a leaflet ported to React, so it is much more manageable. Here’s how you can draw a border or polygon on Map using React leaflet.

1. Install leaflet and react-leaflet to your project

yarn add leaflet react-leaflet

2. Your map would be something like this

import 'leaflet/dist/leaflet.css';
import {MapContainer, Polygon, TileLayer} from "react-leaflet";

<div style={{ width: 100 + "vw", height: 100 + "vh" }}>
  {coordinates.length && (
    <MapContainer
      style={{ width: 100 + "%", height: 100 + "%" }}
      bounds={YOUR_POLYGON_GEO_JSON}
      boundsOptions={{ padding: [1, 1] }}
      scrollWheelZoom={true}
    >
      <TileLayer
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      <Polygon positions={YOUR_POLYGON_GEO_JSON} />
    </MapContainer>
  )}
</div>

3. See the demo and complete source code here on codesandbox.io

Just see the code on the code sandbox above for the full complete code, it shows you all the necessary parts, the package.json, App.js and data.js. Data.js is an example of polygon coordinates, is a bunch of latitudes and longitudes that will make full circle.

The things I like about Javascript or web apps are they are very easy to deploy or run, it can be simulated on the web very easily. Like this one I use codesandbox.io, you can explore and write react apps without the need of installing this build tool in your computer like npm, yarn or even editor, basically you only need a single web browser, writing your code on the browser and it instantly shown to you the results of your codes. That's The beauty of Javascript.

Popular posts from this blog

Spring Kafka - how to use ReplyingKafkaTemplate send and reply synchronously

ERROR 1348 Column Password Is Not Updatable When Updating MySQL Root Password

How To Create Spring Boot Project Using Netbeans

How To Connect SSH Using PEM Certificate On Windows

Upload and Download Rest API using Spring Boot Reactive WebFlux