12
ブラウザでJavaScriptを使用すると、現在地から緯度と経度を持つ別の場所までの距離を調べるにはどうすればよいですか?JavaScriptの既知の場所との距離を見つける方法
ブラウザでJavaScriptを使用すると、現在地から緯度と経度を持つ別の場所までの距離を調べるにはどうすればよいですか?JavaScriptの既知の場所との距離を見つける方法
コードがブラウザで実行された場合、あなたはHTML5ジオロケーションAPIを使用することができます。
window.navigator.geolocation.getCurrentPosition(function(pos) {
console.log(pos);
var lat = pos.coords.latitude;
var lon = pos.coords.longitude;
})
あなたが現在位置とあなたの「ターゲット」の位置がわかれば、あなたはそれらの間の距離を計算することができますこの質問に書かれている方法:Calculate distance between two latitude-longitude points? (Haversine formula)。
だから、完全なスクリプトは次のようになります。
function distance(lon1, lat1, lon2, lat2) {
var R = 6371; // Radius of the earth in km
var dLat = (lat2-lat1).toRad(); // Javascript functions in radians
var dLon = (lon2-lon1).toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
/** Converts numeric degrees to radians */
if (typeof(Number.prototype.toRad) === "undefined") {
Number.prototype.toRad = function() {
return this * Math.PI/180;
}
}
window.navigator.geolocation.getCurrentPosition(function(pos) {
console.log(pos);
console.log(
distance(pos.coords.longitude, pos.coords.latitude, 42.37, 71.03)
);
});
どうやら私は(それがハードコーディングされた第二の場所です)今、ボストン、MAの中心から6643メートルです。
は、より多くの情報のためにこれらのリンクを参照してください。
おかげで多くのことを。もう1つ質問があります。あなたは与えられた場所の緯度と経度を見つけるのを手伝ってくれますか? – Dalee
何を試しましたか? –
私は現在の場所から特定の住所までの距離を見つけようとしていました。とにかく私はそれを見つけた。返信ありがとうございます。 – Dalee