2012-01-18 17 views
9

是去取回使用Bing地圖API或谷歌地圖API的用戶的緯度經度&的方式。我想我看到了一個代碼片段,其中「autolocate我」功能是用來標記在地圖上本身的用戶:獲取用戶使用Bing或者谷歌地圖API的位置(經度,緯度)

var geoLocationProvider = new Microsoft.Maps.GeoLocationProvider(map);   
geoLocationProvider.getCurrentPosition();  

但是,這個功能沒有恢復,它只是在地圖上設置位置的任何數據,而我需要該位置來執行一些計算,即計算哪個預定義位置列表與當前用戶位置最接近。除此之外,這個API的任何一個都可以計算兩個位置之間的距離(lat,lon)作爲輸入嗎?

感謝, 帕維爾

回答

11

讓您的位置不是地圖API的一部分。相反,請使用HTML5 GeoLocation API來獲取您的位置。一個例子是:

navigator.geolocation.getCurrentPosition(locationHandler); 

function locationHandler(position) 
{ 
    var lat = position.coords.latitude; 
    var lng = position.coords.longitude; 
} 

爲了計算緯度/經度點之間的距離,看看http://www.movable-type.co.uk/scripts/latlong.html

// Latitude/longitude spherical geodesy formulae & scripts (c) Chris Veness 2002-2011     - www.movable-type.co.uk/scripts/latlong.html 
// where R is earth’s radius (mean radius = 6,371km); 
// note that angles need to be in radians to pass to trig functions! 
var R = 6371; // km 
var dLat = (lat2-lat1).toRad(); 
var dLon = (lon2-lon1).toRad(); 
var lat1 = lat1.toRad(); 
var lat2 = lat2.toRad(); 

var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
     Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
var d = R * c; 
+0

非常感謝!你能不能也採取了跟進的問題一看:http://stackoverflow.com/questions/8917904/html5-geolocation-api-no-callback-is-called-whatsoever?謝謝! – dragonfly 2012-01-18 21:45:54

+1

只是在有人的情況下,獲得toRad不確定的,看看這個答案:http://stackoverflow.com/a/5260472/879821 – kavain 2015-08-27 23:35:48

0

HTML5 GeoLocation獲取當前位置的緯度和經度。 http://www.w3schools.com/html/html5_geolocation.asp

<!DOCTYPE html> 
<html> 
<body> 

<p id="demo">Click the button to get your coordinates:</p> 
<button onclick="getLocation()">Try It</button> 

<script> 
var x = document.getElementById("demo"); 

function getLocation() { 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(showPosition); 
    } else { 
     x.innerHTML = "Geolocation is not supported by this browser."; 
    } 
} 

function showPosition(position) { 
    x.innerHTML="Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude; 
} 
</script> 

</body> 
</html> 
相關問題