DEV Community

Cover image for Directions with OpenstreetMap
Rakibul Yeasin
Rakibul Yeasin

Posted on

2

Directions with OpenstreetMap

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;
}
Enter fullscreen mode Exit fullscreen mode

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
      })
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

does the thing for you.

So, this was my approach to embed map with directions without spending a penny.

Attributions:

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (1)

Collapse
 
yeasirhossain profile image
Yeasir-Hossain

Thanks for this. Was looking for a guide on how to use leaflet in nextjs 15. It helped a lot.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

If this article connected with you, consider tapping ❤️ or leaving a brief comment to share your thoughts!

Okay