地理定位 WatchPosition 距离计算器

3

我正在使用地理位置技术获取用户当前位置,并使用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);

非常感谢您的帮助,因为我对此还很陌生。
谢谢!
2个回答

3
您可以使用哈弗赛因公式。
rad = function(x) {return x*Math.PI/180;}

distHaversine = function(p1, p2) { // Points are Geolocation.coords objects
  var R = 6371; // earth's mean radius in km
  var dLat  = rad(p2.latitude - p1.latitude);
  var dLong = rad(p2.longitude - p1.longitude);

  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong/2) * Math.sin(dLong/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;

  return d.toFixed(3);
}

两个提示

  1. typeof 不是一个函数。使用方式为:typeof something
  2. 不要将polyfill放在监听器中。这会导致在每次监听器触发时重复进行polyfill操作。

谢谢您的快速回复,Mohsen!我没有使用getCurrentPosition()方法 - 相反,我正在使用watchPosition()。您认为我需要同时使用这两种方法吗? - Liam O'Byrne
@LiamO'Byrne 是的,你可以使用两种方法。 - Foreever

3

这是从Google Maps API改编而来的,并重新设计为独立于库。

示例-计算从纽约市中心到费城中心的距离。

JS

function distanceFrom(points) {
    var lat1 = points.lat1;
    var radianLat1 = lat1 * (Math.PI / 180);
    var lng1 = points.lng1;
    var radianLng1 = lng1 * (Math.PI / 180);
    var lat2 = points.lat2;
    var radianLat2 = lat2 * (Math.PI / 180);
    var lng2 = points.lng2;
    var radianLng2 = lng2 * (Math.PI / 180);
    var earth_radius = 3959; // or 6371 for kilometers
    var diffLat = (radianLat1 - radianLat2);
    var diffLng = (radianLng1 - radianLng2);
    var sinLat = Math.sin(diffLat / 2);
    var sinLng = Math.sin(diffLng / 2);
    var a = Math.pow(sinLat, 2.0) + Math.cos(radianLat1) * Math.cos(radianLat2) * Math.pow(sinLng, 2.0);
    var distance = earth_radius * 2 * Math.asin(Math.min(1, Math.sqrt(a)));
    return distance.toFixed(3);
}

var distance = distanceFrom({
    // NYC
    'lat1': 40.713955826286046,
    'lng1': -74.00665283203125,
    // Philly
    'lat2': 39.952335,
    'lng2': -75.163789
});

结果为 80.524 英里或 129.583 公里。

1
谢谢您的快速回复,Couzzi!我查看了您提供的链接。它们按预期工作,但它们没有使用地理位置。我不确定如何将其操纵以适应我上面的代码。 - Liam O'Byrne
很高兴能够帮助。要使用我的示例,您只需要将包含点A和点B坐标的“对象”传递给distanceFrom()函数。在您的情况下,存储第一个坐标(起始位置),然后,任何后续坐标都将是您的第二个坐标系。每次新的第二个坐标系更改并通过distanceFrom()函数与您的第一个坐标系进行比较时,返回的距离将反映出这一点。 - couzzi
1
所以你的意思是我需要首先使用 getCurrentPosition() 获取用户位置,然后使用 watchPosition() 监控用户移动? - Liam O'Byrne
没错。在第一次运行 watchPosition() 时,你可以将结果存储为“初始”位置,然后继续更新新位置。但同时使用这两种方法也完全可行。 - couzzi
非常感谢您的时间。我将把您的反馈评论标记为答案,所以不用担心!我只有一个问题。我该如何存储watchPosition()的初始位置结果? - Liam O'Byrne
没问题,这里有一个过去的粘贴链接提供概述。 - couzzi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接