2012-12-12 20 views

回答

30

如果你的代碼在瀏覽器中運行,你可以使用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) 
); 
}); 

顯然,我是來自波士頓的中心6643米,MA現在(這是硬編碼的第二個位置)。

請參見以下鏈接瞭解更多信息:

+0

非常感謝。我還有一個查詢。你能幫我找到某個地方的經緯度嗎? – Dalee

+0

你已經試過了什麼? –

+0

我試圖找到從我當前位置到特定地址的距離。無論如何,我發現。謝謝你的回覆。 – Dalee

相關問題