gpt4 book ai didi

javascript - 如何使用 json 数据中的纬度和经度查找最近的位置

转载 作者:太空宇宙 更新时间:2023-11-04 13:50:29 25 4
gpt4 key购买 nike

我正在尝试制作一个网站,询问用户的位置,然后使用 GeoLocation 找到离它的位置最近的位置(半径 100 米),并以 HTML 格式显示结果。

我尝试过的。

$.getJSON("places.json", function (data) {
for (var i = 0; i < data.length; i++) {
if ((data[i].lat - poslat) > 0.00200 || (data[i].lng - poslng) > 0.00200) {
return data[i];
}

html += '<p>' + data[i].location + ' - ' + data[i].code + '</p>';
$('#nearbystops').append(html);
}
});

places.json

[
{
"code": "0001",
"lat": "1.28210155945393",
"lng": "103.81722480263163",
"location": "Stop 1"
},
{
"code": "0003",
"lat": "1.2777380589964",
"lng": "103.83749709165197",
"location": "Stop 2"
},
{
"code": "0002",
"lat": "1.27832046633393",
"lng": "103.83762574759974",
"location": "Stop 3"
}
]

提前致谢! :)

最佳答案

要计算两个坐标之间的距离,您不能只减去这些值。很好,但它会为您提供正方形内的坐标。这可能是合适的,但大多数人确实倾向于按半径搜索位置。这个函数会做到这一点......

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);
if (dist > 1) {
dist = 1;
}
dist = Math.acos(dist)
dist = dist * 180/Math.PI
dist = dist * 60 * 1.1515
if (unit=="K") { dist = dist * 1.609344 }
if (unit=="N") { dist = dist * 0.8684 }
return dist
}

这是我从这里复制的一段普通代码......

https://www.geodatasource.com/developers/javascript

它在这里,用在你的例子中......

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);
if (dist > 1) {
dist = 1;
}
dist = Math.acos(dist)
dist = dist * 180/Math.PI
dist = dist * 60 * 1.1515
if (unit=="K") { dist = dist * 1.609344 }
if (unit=="N") { dist = dist * 0.8684 }
return dist
}

var data = [{
"code": "0001",
"lat": "1.28210155945393",
"lng": "103.81722480263163",
"location": "Stop 1"
}, {
"code": "0003",
"lat": "1.2777380589964",
"lng": "103.83749709165197",
"location": "Stop 2"
}, {
"code": "0002",
"lat": "1.27832046633393",
"lng": "103.83762574759974",
"location": "Stop 3"
}];

var html = "";
var poslat = 1.28210155945393;
var poslng = 103.81722480263163;

for (var i = 0; i < data.length; i++) {
// if this location is within 0.1KM of the user, add it to the list
if (distance(poslat, poslng, data[i].lat, data[i].lng, "K") <= 0.1) {
html += '<p>' + data[i].location + ' - ' + data[i].code + '</p>';
}
}

$('#nearbystops').append(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="nearbystops"></div>

关于javascript - 如何使用 json 数据中的纬度和经度查找最近的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51819224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com