Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate distance between two points in Leaflet

Tags:

How do you calculate the distance between two markers in Leaflet-ionic2?

Couldn't figure out, I hope there is an Algorithme to do as soon as i select a marker it show me the distance between my location and the marker.

Thanks..

like image 798
Taieb Avatar asked Apr 02 '17 10:04

Taieb


People also ask

How do you find a distance between two points?

The formula to find the distance between the two points is usually given by d=√((x2 – x1)² + (y2 – y1)²). This formula is used to find the distance between any two points on a coordinate plane or x-y plane.

Can you find the distance between two points in different dimensions?

The distance between any two points given in two-dimensional plane can be calculated using their coordinates. Distance between two points A(x1,y1 x 1 , y 1 ) and B(x2,y2 x 2 , y 2 ) can be calculated as, d = √[(x2 x 2 − x1 x 1 )2 + (y2 y 2 − y1 y 1 )2].


2 Answers

The Leaflet manual mentions the distanceTo function, which calculates the distance in meters.

Example plagiarized from Google Groups:

function createMarker() {      var markerFrom = L.circleMarker([28.6100,77.2300], { color: "#F00", radius: 10 });      var markerTo =  L.circleMarker([18.9750,72.8258], { color: "#4AFF00", radius: 10 });      var from = markerFrom.getLatLng();      var to = markerTo.getLatLng();      markerFrom.bindPopup('Delhi ' + (from).toString());      markerTo.bindPopup('Mumbai ' + (to).toString());      map.addLayer(markerTo);      map.addLayer(markerFrom);      getDistance(from, to); }  function getDistance(from, to) {     var container = document.getElementById('distance');     container.innerHTML = ("New Delhi to Mumbai - " + (from.distanceTo(to)).toFixed(0)/1000) + ' km'; } 
like image 98
aggregate1166877 Avatar answered Sep 25 '22 12:09

aggregate1166877


You can use this function to find distance between 2 position.

function getDistance(origin, destination) {     // return distance in meters     var lon1 = toRadian(origin[1]),         lat1 = toRadian(origin[0]),         lon2 = toRadian(destination[1]),         lat2 = toRadian(destination[0]);      var deltaLat = lat2 - lat1;     var deltaLon = lon2 - lon1;      var a = Math.pow(Math.sin(deltaLat/2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(deltaLon/2), 2);     var c = 2 * Math.asin(Math.sqrt(a));     var EARTH_RADIUS = 6371;     return c * EARTH_RADIUS * 1000; } function toRadian(degree) {     return degree*Math.PI/180; } var distance = getDistance([lat1, lng1], [lat2, lng2]) 

We are using this function in our library time-aware-polyline to encode lat lng info with timestamp.

like image 21
Gaurav Mukherjee Avatar answered Sep 23 '22 12:09

Gaurav Mukherjee