1
ユーザーのジオロケーションを取得するスクリプトを作成し、Haversine式を使用してオブジェクト内のアイテムとアイテム間の距離を計算し、距離をconsole.logにします。私の質問は、どうすればconsole.logに最も近い項目だけですか?誰かが助けることができると思います:) showDistance()
でジオロケーションに基づいて最寄りの距離を取得
<!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>
素晴らしい! Daveさん、ありがとうございました:) – hb8