最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the distance between two locations based on their latitude and longitude? - Stack Overflow

programmeradmin2浏览0评论

I am trying to display a list based on user distance to each location. The locations are received from Firebase as a JSON.

To get user location, I'm using:

    navigator.geolocation.getCurrentPosition(function(position) {
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;

Do you know a way to sort this JSON by distance and list it (having multiple child nodes)?

Thanks.

I am trying to display a list based on user distance to each location. The locations are received from Firebase as a JSON.

To get user location, I'm using:

    navigator.geolocation.getCurrentPosition(function(position) {
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;

Do you know a way to sort this JSON by distance and list it (having multiple child nodes)?

Thanks.

Share Improve this question edited Oct 13, 2017 at 19:52 Khalil Khalaf 9,39712 gold badges67 silver badges108 bronze badges asked Oct 13, 2017 at 5:52 featorresfeatorres 231 silver badge3 bronze badges 3
  • do you receive a list of {lat, lng} as well? – Khalil Khalaf Commented Oct 13, 2017 at 6:02
  • Yes, I receive a list of {lat, lng, ... } for each location. – featorres Commented Oct 13, 2017 at 6:23
  • I will write you the answer – Khalil Khalaf Commented Oct 13, 2017 at 13:27
Add a ment  | 

1 Answer 1

Reset to default 11

You have two ways to get the distance between a latitude/longitude to some other latitude/longitude:

- Using Google API

    function getDistanceOneToOne(lat1, lng1, lat2, lng2)
    {
       const Location1Str = lat1 + "," + lng1;
       const Location2Str = lat2 + "," + lng2;

       let ApiURL = "https://maps.googleapis./maps/api/distancematrix/json?";

       let params = `origins=${Location1Str}&destinations=${Location2Str}&key=${GOOGLE_API_KEY}`; // you need to get a key
       let finalApiURL = `${ApiURL}${encodeURI(params)}`;

       let fetchResult =  await fetch(finalApiURL); // call API
       let Result =  await fetchResult.json(); // extract json

       return Result.rows[0].elements[0].distance;
    }

This requires network connection on the mobile, but it provide the driving distance(exactly as the driving navigator) PLUS more information (ex, duration to arrive), unlike the second approach which provides the straight distance.

For the above you need to get a Google Api Key. More info here: Google Maps Api

- Using Pure Math

This happens locally on the devices, and it provides the straight distance between two latitudes/longitudes.

function distance(lat1, lon1, lat2, lon2, unit) {
    var radlat1 = Math.PI * lat1/180
    var radlat2 = Math.PI * lat2/180
    var theta = lon1-lon2
    var radtheta = Math.PI * theta/180
    var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
    dist = Math.acos(dist)
    dist = dist * 180/Math.PI
    dist = dist * 60 * 1.1515
    if (unit=="K") { dist = dist * 1.609344 }
    if (unit=="M") { dist = dist * 0.8684 }
    return dist
}

Run one of the above for each item and you will get the distance for each. Hope that helps.

发布评论

评论列表(0)

  1. 暂无评论