使用Bing或Google Maps API获取用户的位置(纬度,经度)

9

是否有一种方法可以使用Bing Maps API或Google Maps API检索用户的纬度和经度。 我记得我曾经看到过一个代码片段,其中“自动定位我”功能被用来在地图上标记用户本身:

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

但是该函数并不返回任何数据,它只是在地图上设置位置,而我需要这个位置来执行一些计算,即计算预定义的地点列表中哪个地点离当前用户位置最近。除此之外,这些API中是否有任何一个可以计算提供为输入的两个位置(纬度、经度)之间的距离?谢谢,Pawel。
2个回答

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;

非常感谢!您能否也看一下后续问题:http://stackoverflow.com/questions/8917904/html5-geolocation-api-no-callback-is-called-whatsoever?谢谢! - dragonfly
1
如果有人遇到了“toRad未定义”的情况,请查看此答案:https://dev59.com/uG435IYBdhLWcg3wtSYV#5260472 - 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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接