簡體   English   中英

如何使用我的位置使用經度和緯度計算兩點之間的距離

[英]How to use my location to calculate distance between two points using latitude and longitude

我正在嘗試使我的REST API僅向我發送在一定半徑內的項目。 我已經編寫了代碼來計算兩點之間的距離,並且只向我發送所需半徑內的距離。 但是,到目前為止,我使用任意緯度和經度作為比較點。 如何使用自己的位置實現此算法?

app.get('/posts', function(req, res) { 

// Get 'posts' collection from db
db.collection('posts', function(err, collection) { 

    // Get all documents in the 'posts' collection
    collection.find().toArray(function(err, items) {

        // Documents to send back
        var results = []

//Function that calculates distance between two points.
    function calculateDistance (lat1, lat2, lon1, lon2) {
        var dLat = deg2rad(lat2-lat1);  
        var dLon = deg2rad(lon2-lon1); 
        var a = 
            (Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
            Math.sin(dLon/2) * Math.sin(dLon/2))
            ; 
        var c = (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))); 
        var d = (6371 * c); // Distance in km
        var e = (d/1.6) //Convert distance in km to miles.
            return e 
    }

        // Iterate over each document and check if the distance is correct
        for (var i = 0; i < items.length; i++) {
            var item = items[i]
             if ((calculateDistance(item.latitude, 43.7035798, item.longitude, -72.2887838) > 25)) {
                 results.push(item)
             }

        }          
        res.send(results);
    });
});
});

navigator.geolocation是您想要的。

https://developer.mozilla.org/zh-CN/docs/Web/API/Geolocation/Using_geolocation

至少在Firefox中,您應該看到一個彈出窗口,詢問您是否要允許瀏覽器發送位置信息。 您可能已經為使用Google Maps API的網站獲得了它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM