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..
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.
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].
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'; }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With