2012-12-12 5 views
12

브라우저에서 JavaScript를 사용하면 현재 위치에서 위도와 경도가있는 다른 위치까지의 거리를 어떻게 결정할 수 있습니까? 현재 위치와 당신의 "대상"의 위치를 ​​알게되면JavaScript에서 알려진 위치까지의 거리를 찾는 방법

window.navigator.geolocation.getCurrentPosition(function(pos) { 
    console.log(pos); 
    var lat = pos.coords.latitude; 
    var lon = pos.coords.longitude; 
}) 

, 당신은 그들 사이의 거리를 계산할 수 있습니다 코드를 브라우저에서 실행하는 경우

답변

30

, 당신은 HTML5의 위치 정보 API를 사용할 수 있습니다 이 질문에 문서화 된 방법 : 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) 
); 
}); 

은 분명히 내가 보스턴의 중심에서 6,643m 오전, MA 지금 (즉 하드 코딩 된 두 번째 위치).

자세한 내용은 다음 링크를 참조하십시오 :

+0

덕분에 많이. 하나 이상의 쿼리가 있습니다. 주어진 장소의 위도와 경도를 찾는 데 나를 도울 수 있습니까? – Dalee

+0

당신은 무엇을 이미 시도 했습니까? –

+0

현재 위치에서 특정 주소까지의 거리를 찾으려고했습니다. 어쨌든 나는 그것을 발견했다. 답장을 보내 주셔서 감사합니다. – Dalee

관련 문제