Recently we got a project which requires an embedded map with directions. The decision was obvious, use google maps direction api. But when approached the client with the pricing, he simply sat back. He doesn't want to spend a penny on map.
Now, as always I had to find a way to do it for free. The first thing came to my thought was openstreet map. It's a community-driven opensource project and completely free. Some api's are paid as they are hosted by third party. But the map is free.
The project was using next.js v15. We used leaflet (another opensource project from Ukraine) to integrate openstreet map. It has a React wraper on top it named 'react-leaflet'. For showing the direction layer we used 'leaflet-routing-machine'.
This is the final project we have (removed some code from the original source).
There is a catch. leaflet breaks the map if we just follow their guide. We have to do some extra job to make it work. We have to import 'leaflet/dist/leaflet.css' to our component. But the best thing we can do is import the stylesheet in our main css like this: @import 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css';
And override the leaflet container class:
.leaflet-container {
width: 100vh;
height: 100vh;
}
The routing machine adds marker to the start and end point by default. We can hide those by passing
plan: routingMachine.plan(waypoints, {
createMarker: () => false // This prevents the routing markers from appearing
})
to our routingMachine.controll
options.
If you don't want the "itinerary instructions", there is not straight way to do it (I didn't find). But you can always override css. So,
.leaflet-routing-alternatives-container {
display: none;
}
does the thing for you.
So, this was my approach to embed map with directions without spending a penny.
Attributions: