【问题标题】:Geolocation WatchPosition Distance Calculator地理位置观察位置距离计算器
【发布时间】:2013-03-28 09:57:42
【问题描述】:

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

非常感谢任何帮助,因为我对此很陌生。

谢谢!

【问题讨论】:

    标签: javascript html geolocation distance


    【解决方案1】:

    这已改编自 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 公里。

    【讨论】:

    • 感谢您的快速回复 Couzzi!我查看了您提供的链接。它们按预期工作,但不使用地理位置。我很困惑如何操纵它以适应上面的代码。
    • 很高兴我能帮上忙。要使用我的示例,您只需将 object 传递给 distanceFrom() 函数,其中包含点 A 的坐标和点 B 的坐标。在您的情况下,存储 first 集坐标(您的起始位置),然后,任何以下坐标将是您的第二组。每次新的 second 组发生变化并与您的 first 组坐标进行比较(通过distanceFrom() 函数),返回的距离将反映这一点。
    • 所以你说的是我需要首先使用 getCurrentPosition() 获取用户位置。那么,使用 watchPosition() 来监控用户的移动?
    • 没错。您可以,在watchPosition() 第一次运行时,将结果存储为“初始”位置,然后继续更新新位置。但是使用这两种方法都可以完美地工作。
    • 非常感谢您抽出宝贵时间。我会将您的标记反馈评论作为答案,所以不要担心!我还有一个问题。如何存储 watchPosition() 的初始位置结果?
    【解决方案2】:

    你可以使用Haversine公式

    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()。你认为我需要同时使用这两种方法吗?
    • @LiamO'Byrne 是的,您可以同时使用这两种方法。
    猜你喜欢
    • 2014-01-05
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 2011-04-03
    • 2020-01-28
    • 2020-07-16
    相关资源
    最近更新 更多