Google javascript映射getCurrentPosition
如何使用:Google javascript映射getCurrentPosition,javascript,google-maps,Javascript,Google Maps,如何使用: navigator.geolocation.getCurrentPosition() 获取当前位置的坐标。 这是来自谷歌网站的示例: function initialize() { var mapOptions = { zoom: 6 }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); // Try HTML5 geolocation if(na
navigator.geolocation.getCurrentPosition()
获取当前位置的坐标。这是来自谷歌网站的示例:
function initialize() {
var mapOptions = {
zoom: 6
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
我尝试将var pos部分替换为myPos,这是一个全局变量,但没有成功。我的意思是我总是在initialize()函数之后得到未定义的myPos。
在窗体(窗口)加载时调用的初始化函数中,获取纬度和经度navigator.geolocation.getCurrentPosition()的正确方法是什么
.getCurrentPosition()
是一个异步函数,因此它接受一个回调,该回调在具有这些坐标后执行,例如
navigator.geolocation.getCurrentPosition(function(position){
console.log(position);
});
这会给你类似的东西:
{
"timestamp": 1421093714138,
"coords":
{
"speed": null,
"heading": null,
"altitudeAccuracy": null,
"accuracy": 20,
"altitude": null,
"longitude": -122.4091036,
"latitude": 37.7837543
}
}
var myPos;
navigator.geolocation.getCurrentPosition(function(position){
myPos = position;
});
在回调中传递.getCurrentPosition
,您甚至可以更新变量,前提是它们是预先声明的。我猜您的myPos
变量未定义的原因是您连接到google maps API的方式存在问题。如果您不使用谷歌地图,只想获得一个位置,您可以这样做:
{
"timestamp": 1421093714138,
"coords":
{
"speed": null,
"heading": null,
"altitudeAccuracy": null,
"accuracy": 20,
"altitude": null,
"longitude": -122.4091036,
"latitude": 37.7837543
}
}
var myPos;
navigator.geolocation.getCurrentPosition(function(position){
myPos = position;
});
哦,确保你允许网站访问你的位置。在chrome浏览器中,页面顶部会出现一个栏,上面写着“tmpPos
。如上所述,.getCurrentPosition
是一个函数。这意味着它建立了一个过程来获取你的地理位置,但同时做其他事情(在你的情况下,它会继续并尝试将其他变量更新为它还没有的信息)
此外,您在其内部调用initialize函数,这样将创建一个永不结束的无限循环函数。要解决此问题,请尝试:
function initialize(){
navigator.geolocation.getCurrentPosition(function(position){
// create the map here, because we only have access to position inside of this function
// even if we store in a global variable, it only gets updated once this callback runs
var currentPosition = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
}
initialize();
我现在在myPos中得到了一个地理位置对象,但是如果我尝试使用myPos.coords.latitude访问latitude,我会得到一个异常:“Uncaught TypeError:无法读取undefined的属性'coords',尽管如果我打开变量,有coords部分,我可以看到纬度和经度数字。请参阅[有一些地方出错。更新了我的答案。查看此资源(javascriptissexy.com/understand javascript回调函数并在回调上使用它们/),我认为这将帮助您全面了解异步JS编码模式地理定位服务是异步的(因此,在回调函数运行之前不会定义位置)。也许你是对的,我如何告诉函数在调用getcurrentposition之前不会继续?你要求获取一个异步函数,它是异步的,这是有原因的,并使其同步…研究/理解异步函数。