2012-01-18 8 views
9

のユーザーの位置(緯度、経度)を取得するには、Bing Maps APIまたはGoogle Maps APIを使用してユーザーの緯度&の経度を取得する方法があります。一方で、それは単に地図上の場所を設定し、BingまたはGoogle Maps APIで

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

しかし、その関数はデータを返しません:私は、「私をAUTOLOCATE」機能は地図自体にユーザーをマークするために使用されたコードスニペットを見たと思います私はいくつかの計算を実行するためにその場所が必要です。つまり、事前定義された場所のリストのどれが現在のユーザーの場所に最も近いかを計算します。それとは別に、このAPIは入力として提供される2つの場所(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

+1

toRadが未定義の場合は、この回答を確認してください:http://stackoverflow.com/a/5260472/879821 – kavain

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>