📜 ⬆️ ⬇️

Build routes with OpenStreetMap, OSRM and Leaflet

Hi% username%! I want to write a small article about how to use OpenStreetMap, OSRM and Leaflet to create routes in your project. I will not tell what the above technologies are - I’ve written about them more than once already, the article will be small and only relevant. So, if you want to build routes - please under the cat.

image

So let's get started. To work, we need JQuery and Leaflet. The latter can be taken on the official website - leafletjs.com
If you wish, you can use CDN (I’d just note that it loads quite quickly).

<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" /> 

 <script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script> 

')
Next we need a container where the map will be loaded. Create a div and give it a map id

 <div id="map"></div> 


If necessary, it can set the width / height, use in pop-up windows, etc.
Now directly initialization - we bind the map to our div.

 var map = L.map('map'); 


After that the map is loaded into our div. But what in this case will load Leaflet? Obviously not the city where we are. To fix this, we write the following code:

 map.setView([55.7422, 37.5719], 11); 


This design will load us a map of Moscow (coordinates must be inserted in the LatLng sequence, zoom), where zoom is the scale. Oh yeah, I almost forgot - we need to specify where to get the images for the map. Sources can be very different, from the official site to your own server. Take the official website:

 L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(map); 


At this stage we have in our div loaded map of the city we need. Now let's start building routes. To begin with, we will add a marker by clicking on the map. In total there will be 2 markers - for the beginning of the path and the end, we will not do routing with several points for now. So, we need to handle the 'click' event on the map. I implemented it like this:

 map.on('click', function(e) { onMapClick(e); }); function onMapClick(e) { if (loc1 == null) { loc1 = new L.marker(e.latlng, {draggable: 'true'}); loc1.on('dragend', function(event) { //   }); map.addLayer(loc1); } else if (loc2 == null) { loc2 = new L.marker(e.latlng, {draggable: 'true'}); loc2.on('dragend', function(event) { //   }); map.addLayer(loc2); //   } } ; 


After clicking on the map, the onMapClick function checks whether the points loc1 and loc2 exist. If both points exist, only the movement of the marker on the map ('dragend') is tracked. Dragging itself is enabled using the draggable: 'true' parameter. There are markers, dragging is tracked, it remains only to fasten the drawing of the route. Where to send a request is up to you, you can use OSRM (and I strongly advise you that this is a free tool with high speed). I use my own server, which gives me the result of a polyline line. On the Internet, there is a ready implementation for all the PLs for decoding this string into an array of values. How to implement it in your case is up to you. My decoding is done using php and the result is returned as an array of coordinates. So, the method of sending requests and drawing routes:

 var polyline; function sendPost() { if (loc2 != null && loc1 != null) { var p1 = loc1.getLatLng(), p2 = loc2.getLatLng(); $.post( //  , {l1: p1.lat + ',' + p1.lng, l2: p2.lat + ',' + p2.lng}, function(data) { if (data) { if (polyline) { map.removeLayer(polyline); } var points = data; polyline = new L.polyline(points, {color: 'red'}); map.addLayer(polyline); map.fitBounds(polyline.getBounds()); } }, "json" ); } } 


I admit at once - I know javascript extremely terribly, but you probably already understood this. But we will continue. Set the polyline variable, which we will use later to create the route line. The line will be added with a new layer so that when dragging, you can delete the old route. If the request is successfully completed, the check is in progress - there is already a layer or not. If it exists (i.e. there is already a route), the new one is deleted and built.

That's basically it. I ask experienced programmers not to swear much - the article is more focused on beginners like me. When performing this task, I was faced with the lack of examples in the network for constructing routes using this library and other minor nuances that I encountered. I will be happy to answer all your questions and add what you think I missed.

Source: https://habr.com/ru/post/230951/


All Articles