根据地理位置获取最近的距离

Get nearest distance based on geolocation

我制作了一个脚本来获取用户的地理位置,使用 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>

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 post,它解释了如何从数组中获取最小值:Obtain smallest value from array in Javascript?

希望对您有所帮助!