Measuring distance between specific and current position with html5
As the title suggests. Any idea how to accomplish that?
Been looking at http://www.html5archive.com/2010/12/04/geolocation-api-exa开发者_高级运维mple-distance-tracking/ for a while and trying to modify that code, but with no luck.
It doesn't need to be auto refreshing initially.
But basic function should get user location and tell distance between the user and the specific point.
The key code is on this page linked from the one you specified. I've converted it to a function below:
/** Extend Number object with method to convert numeric degrees to radians */
if (typeof Number.prototype.toRadians == 'undefined') {
Number.prototype.toRadians = function() { return this * Math.PI / 180; };
}
function getDistance(lat1,lon1,lat2,lon2) {
var R = 6371; // km
var dLat = (lat2-lat1).toRadians();
var dLon = (lon2-lon1).toRadians();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRadians()) * Math.cos(lat2.toRadians()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
}
You need to pass it the specific lat and lon as the first two parameters, and the current lat and lon as the second two.
精彩评论