perliedman/leaflet-routing-machine

How is it possible to calculate distance from a route ?

Closed this issue · 6 comments

Hi,

I have to calculate distance from an address between route.

https://www.lamaraudiere.com/d4ua/cartographie.php

How is it possible ?

I'm not sure I understand the question. The route request already returns the total distance and distance between points as can be seen in the example

Hi @curtisy1 ,

I have to find distance from a point to route.

Okay, so looking at the source code from your website sample, you have a situation where you have a few waypoints and you do something with geolocation. I'm also seeing a distanceFromAddress function that seems to work just fine. If I run it in the console, my current position or the one I specified gets added to the route's waypoint and osrm returns the new route properly.

Or is the question unrelated to LRM and you just want the distance from point A to B in general? Then you can do

L.latLng(routes[j].options.waypoints[0].lat, routes[j].options.waypoints[0].lng).distanceTo(L.latLng(document.getElementById("latitude").value, document.getElementById("longitude").value))

Hi @curtisy1 ,

Many thanks for "distanceTo", but I want to know the distance from a point to route, the minimal distance to route.
As you can see, If you choice the select "distance" that add circle.

I have to know if points of route are in the distance of my address.

I tried that, but it is for a segment route not for route :

MyAddressLat = document.getElementById("latitude").value;
MyAddressLng = document.getElementById("longitude").value;

		PointMyAddress = mymap.latLngToLayerPoint(L.latLng(MyAddressLat, MyAddressLng));
		
		for (j=0 ; j < routes.length ; j++) {
			
			waypoint0Lat = routes[j].options.waypoints[0].lat;
			waypoint0Lng = routes[j].options.waypoints[0].lng;
			
			Point0 = mymap.latLngToLayerPoint(L.latLng(waypoint0Lat, waypoint0Lng));
			
			waypoint1Lat = routes[j].options.waypoints[1].lat;
			waypoint1Lng = routes[j].options.waypoints[1].lng;
			
			Point1 = mymap.latLngToLayerPoint(L.latLng(waypoint1Lat, waypoint1Lng))
			
			distancePixels = L.LineUtil.pointToSegmentDistance(PointMyAddress, Point0, Point1);
			p1 = mymap.layerPointToLatLng([0, 0]);
			p2 = mymap.layerPointToLatLng([distancePixels, 0]);
			distanceKm = p1.distanceTo(p2);
			distanceKm = ((distanceKm) / 1000).toFixed(2);
			
			console.log(distanceKm + " " + PointMyAddress + " " + Point0 + " " + Point1);
		}

Hi @curtisy1 ,

I found, the points are in route.coordinates.

Many thanks for your helps.

Great to hear you solved it! I'll go ahead and close the issue. Feel free to reopen it if you think the question is still not answered