Algorithm to calculate the nearest location (from the database) based on logitude & latitude

拜拜、爱过 提交于 2019-12-24 20:48:54

问题


What i want to do is develop an algorithm to calculate which known locations are closest to the selected location. Let's say i have 7 locations in the database and when the user selects one, he should have the option to see the, let's say, first 3 closest locations (from the database). In the database, each location is saved with latitude and longitude.

Any idea on how i can do that?

Example: Say the list contains 100 locations of bike stations. I am at station 5, and I want to find out what other stations in the list lies nearby. Not the distance, but their location.


回答1:


Good question, Let's think we have following three value in DB:

var dataFromDb = [{
    "location": "First location",
    "lat": "1.28210155945393",
    "lng": "103.81722480263163",

}, {
    "location": "Second location",
    "lat": "1.2777380589964",
    "lng": "103.83749709165197",
    "location": "Stop 2"
}, {
    "location": "Third Location",
    "lat": "1.27832046633393",
    "lng": "103.83762574759974",
}];

Create a function for the distance between two places:

function distanceBetweenTwoPlace(firstLat, firstLon, secondLat, secondLon, unit) {
        var firstRadlat = Math.PI * firstLat/180
        var secondRadlat = Math.PI * secondLat/180
        var theta = firstLon-secondLon;
        var radtheta = Math.PI * theta/180
        var distance = Math.sin(firstRadlat) * Math.sin(secondRadlat) + Math.cos(firstRadlat) * Math.cos(secondRadlat) * Math.cos(radtheta);
        if (distance > 1) {
            distance = 1;
        }
        distance = Math.acos(distance)
        distance = distance * 180/Math.PI
        distance = distance * 60 * 1.1515
        if (unit=="K") { distance = distance * 1.609344 }
        if (unit=="N") { distance = distance * 0.8684 }
        return distance
}

Define current place:

var currentLat = 1.28210155945393;
var currentLng = 103.81722480263163;

Find Records within 1KM:

for (var i = 0; i < data.length; i++) {
    if (distance(currentLat, currentLng, data[i].lat, data[i].lng, "K") <= 1) {
        console.log(data[i].location);
    }
}



回答2:


You can view a great example on how to calculate it here.

From this site:

var R = 6371e3; // metres
var φ1 = lat1.toRadians();
var φ2 = lat2.toRadians();
var Δφ = (lat2-lat1).toRadians();
var Δλ = (lon2-lon1).toRadians();

var a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
        Math.cos(φ1) * Math.cos(φ2) *
        Math.sin(Δλ/2) * Math.sin(Δλ/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

var d = R * c; //<-- distance between lat1/lon1 and lat2/lon2


来源:https://stackoverflow.com/questions/56111647/algorithm-to-calculate-the-nearest-location-from-the-database-based-on-logitud

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!