我正在使用地理位置来获取用户的当前位置并使用 watchPosition 方法对其进行监控。但是,有没有办法计算用户起始位置和当前位置之间的距离?下面是我的代码:
var x = document.getElementById("info");
function getLocation() {
if(navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition, showError, {
enableHighAccuracy: true,
maximumAge: 60000,
timeout: 27000
})
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
var flightPathCoordinates = [];
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude + "<br>Accuracy: " + position.coords.accuracy + "<br>Altitude: " + position.coords.altitude + "<br>Altitude Accuracy: " + position.coords.altitudeAccuracy + "<br>Heading: " + position.coords.heading + "<br>Speed: " + position.coords.speed + "<br>Speed (mph): " + position.coords.speed * 2.2369 + "<br>Speed (km): " + position.coords.speed * 3.6 + "<br>Timestamp: " + new Date(position.timestamp).toLocaleString() + "<br>Distance Travelled (km): " + calculateDistance(position.coords.latitude, position.coords.longitude, position.coords.latitude, position.coords.longitude);
// Distance Calculator
function calculateDistance(lat1, lon1, lat2, lon2) {
if(typeof (Number.prototype.toRad) === "undefined") {
Number.prototype.toRad = function () {
return this * Math.PI / 180;
}
}
var R = 6371; // km
var dLat = (lat2 - lat1).toRad();
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;
return d;
}
Number.prototype.toRad = function () {
return this * Math.PI / 180;
}
lat = position.coords.latitude;
lon = position.coords.longitude;
latlon = new google.maps.LatLng(lat, lon)
mapholder = document.getElementById('mapholder')
var myOptions = {
center: latlon,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
}
var map = new google.maps.Map(document.getElementById("mapholder"), myOptions);
任何帮助将不胜感激,因为我对此很陌生。
谢谢!