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.

Comments

Popular posts from this blog

Flutter Button With Left Align Text and Icon

How To Create Flutter Card With Example Code

ASUS Battery Health Charging Software To Make Your Battery Life Longer

How To Uninstall Angular CLI, The Angular Framework

Flutter AppBar, With Icon, Title and Actions Link