我创建了一个脚本,用于获取用户的地理位置,使用Haversine公式计算对象中位置和项目之间的距离,然后使用console.log计算距离。我的问题是我怎样才能在console.log中找到最近的项目?希望有人可以提供帮助:)
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<p id="demo"></p>
<script>
var obj = [
{
name:"location1",
lat:60.413750,
long:5.322036
},
{
name:"location2",
lat:59.749054,
long:10.203781
},
{
name:"location3",
lat:59.286271,
long:11.109228
},
{
name: "location4",
lat:59.913869,
long:10.752245
}
];
var x = $("#demo");
var hblat ;
var hblong ;
var distance ;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showDistance);
} else {
x.html("Geolocation is not supported by this browser.");
}
function showDistance(position) {
hblat = position.coords.latitude;
hblong = position.coords.longitude;
$.each(obj, function(key, value){
distance = hbdistance(hblat, hblong, value.lat, value.long, 'K');
console.log(Math.round(distance*1000)/1000);
});
}
function hbdistance(lat1, lon1, lat2, lon2, unit) {
var radlat1 = Math.PI * lat1/180
var radlat2 = Math.PI * lat2/180
var radlon1 = Math.PI * lon1/180
var radlon2 = Math.PI * lon2/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=="N") { dist = dist * 0.8684 }
return dist
}
</script>
</body>
</html>
答案 0 :(得分:0)
在showDistance()
中,您有一个each
区块,您可以在其中计算距离并且看起来正确。你甚至将它们登录到控制台,所以我们几乎就在那里。
我们在这里使用一个简单的解决方案并构建一系列距离:
function showDistance(position) {
hblat = position.coords.latitude;
hblong = position.coords.longitude;
var distances = []; // Array to store distances
$.each(obj, function(key, value){
distance = hbdistance(hblat, hblong, value.lat, value.long, 'K');
distances.push(distance); // Add our distance to the array
});
var min = Math.min.apply(Math, distances); // Get minimum value
console.log(min); // Log minimum value
}
您可以看到另一个SO帖子,其中解释了从数组中获取最小值:Obtain smallest value from array in Javascript?
希望有所帮助!