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

dra*_*fly 9 google-maps geolocation bing-maps

有没有办法使用Bing Maps API或Google Maps API检索用户的纬度和经度.我想我看到了一个代码片段,其中"自动定位我"功能用于在地图上标记用户:

var geoLocationProvider = new Microsoft.Maps.GeoLocationProvider(map);  
geoLocationProvider.getCurrentPosition(); 
Run Code Online (Sandbox Code Playgroud)

但是该函数不返回任何数据,它只是在地图上设置位置,而我需要该位置来执行一些计算,即计算哪个预定义的位置列表最接近当前用户位置.除此之外,这个API中的任何一个都可以计算作为输入提供的两个位置(lat,lon)之间的距离吗?

谢谢,Pawel

Kev*_*vin 11

获取您的位置不是Map API的一部分.而是使用HTML5 GeoLocation API来获取您的位置.一个例子是:

 navigator.geolocation.getCurrentPosition(locationHandler);

 function locationHandler(position)
 {
   var lat = position.coords.latitude;
   var lng = position.coords.longitude;
 }
Run Code Online (Sandbox Code Playgroud)

要计算纬度/经度点之间的距离,请查看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;
Run Code Online (Sandbox Code Playgroud)