API获取用户的位置

API获取用户的位置

本文介绍了使用Bing或Google Maps API获取用户的位置(经度,纬度)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法检索纬度&用户使用Bing Maps API或Google Maps API的经度。我认为我看到了一个代码片段,其中使用了autolocate me功能来标记Map上的用户:

  var geoLocationProvider =新Microsoft.Maps.GeoLocationProvider(地图); 
geoLocationProvider.getCurrentPosition();

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



谢谢,
Pawel

解决方案

获取您的位置不是Map API的一部分。请改用来获取您的位置。一个例子是:

  navigator.geolocation.getCurrentPosition(locationHandler); 

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

要计算纬度/经度点之间的距离,请查看

  //纬度/经度球形大地测量公式&脚本(c)Chris Veness 2002-2011  -  www.movable-type.co.uk/scripts/latlong.html 
//其中R是地球半径(平均半径= 6,371km);
//注意角度需要以弧度传递以触发函数!
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;


is there a way to retrieve a latitude & longitude of the user using Bing Maps API or Google Maps API. I think I saw an code snippet where a "autolocate me" feature was used to mark user on the Map itself:

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

But that function doesn't return any data, it simply set location on the map, whereas I need that location to perform some calculations, namely calculate which of predefined list of places is the closest to current user location. Apart from that, does any of this API's can calculate the distance between two locations (lat,lon) that are provided as an input?

Thanks,Pawel

解决方案

Getting your location isn't part of the Map API. Instead, use the HTML5 GeoLocation API to get your location. An example would be:

 navigator.geolocation.getCurrentPosition(locationHandler);

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

For calculating distance between lat/lng points, have a look at 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;

这篇关于使用Bing或Google Maps API获取用户的位置(经度,纬度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 06:26