I found this nice script from here to calculate the distance between me and other locations.
Script:
function distance(lat1, lon1, lat2, lon2) {
var R = 6371; // Radius of the earth in km
var dLat = (lat2-lat1).toRad(); // Javascript functions in radians
var dLon = (lon2-lon1).toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
/** Converts numeric degrees to radians */
if (typeof(Number.prototype.toRad) === "undefined") {
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
}
window.navigator.geolocation.getCurrentPosition(function(pos) {
console.log(pos);
console.log(
distance(pos.coords.latitude, pos.coords.longitude, lat2, lon2)
);
});
My HTML looks like this:
<div class="map" data-latLng="86.55,79.66">Distance:<i></i></div>
<div class="map" data-latLng="96.55,89.66">Distance:<i></i></div>
<div class="map" data-latLng="116.55,179.66">Distance:<i></i></div>
At "[i]" I want to show the distance. So, my problems are:
so far I only work with jQuery, how can I get the [data-latLng] by "var", something like
"var lat2 = $("div").attr("data-latLng");"
seemes not to work in javascript?how can I split the "data-latLng" into "lat2" and "lon2" for the function?
is there any ".each" function for javascript to do this for all my loactions?