根据对数和距离计算最近位置(从数据库中)的算法.纬度 [英] Algorithm to calculate the nearest location (from the database) based on logitude & latitude
问题描述
我想做的是开发一种算法来计算哪些已知位置最接近所选位置. 假设我在数据库中有7个位置,当用户选择一个位置时,他应该可以选择查看(从数据库中)最近的3个位置.在数据库中,每个位置均按纬度和经度保存.
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?
示例:说该列表包含100个自行车站点位置.我在5号车站,我想找出列表中其他哪些车站在附近.不是距离,而是它们的位置.
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.
推荐答案
好问题,我们认为在数据库中有以下三个值:
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
}
定义当前地点:
var currentLat = 1.28210155945393;
var currentLng = 103.81722480263163;
查找1公里内的记录:
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);
}
}
这篇关于根据对数和距离计算最近位置(从数据库中)的算法.纬度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!