Route Planning Using Open Street Map
Introduction
In this blog post, we will delve into the utilization of Leaflet.js, an open-source JavaScript library, in conjunction with React to craft interactive maps as a substitute for Google Maps. Understanding the application of Leaflet.js can enable us to showcase location data effectively and construct personalized map-centric applications effortlessly.
For this tutorial and into the future, we’ll employ the following tools:
- Leaflet
A JavaScript library for interactive maps - React
A JavaScript library for building user interfaces - React-Leaflet
React components for Leaflet maps
What is Leaflet?
Leaflet stands out as the premier open-source JavaScript library tailored for mobile-responsive interactive maps. With a compact size of approximately 42 KB of JS, it encompasses all the essential mapping functionalities most developers require.
Engineered with simplicity, performance, and user-friendliness at its core, Leaflet seamlessly operates across all key desktop and mobile platforms. It offers extensive extensibility through numerous plugins, boasts an attractive, intuitive API with thorough documentation, and features a straightforward, readable source code that fosters enjoyable contributions.
Integration
We can install the package for react-leaflet by following the command.
npm install react-dom leaflet
This will help to setup the map
Setting Up the Map
First, change the App.js file with the following code to have basic components invoked for the map.
Following is the file structure for the sample application
Map Integration starts from <MapSearch /> Component
Please create <MapContainer /> file and copy following code
For Creating Routes between two points, the <RoutePlanner /> component is created.
The “react-bootstrap” library is used for form control inputs, and React Select will display the search result from geolocation.
This will be responsible for letting geo-search by text using “leaflet-geo search,” and save the start and end location in React Context.
“leaflet-routing-machine” will highlight the road between the coordinates provided.
With complete integration final output of the route planning will be as follows:-
Note: Leaflet map container component must have fixed height and width otherwise the map may not be visible properly.
You may find the GitHub repo link for the complete sample project here branch name: route-planning
Conclusion
It is safe to say that React-leaflet may not be able to provide all the features that other paid libraries have. But it has the ability to be of use when one may need an open source alternative map library for Basic Tracking Applications or Home Delivery and many more use cases.