Google Map同步地址解析延迟 [英] Google map sync geocode delay
问题描述
就是这样, jsfiddle
如您所见,我打算为Google地图功能创建单独的功能. locate_self()
函数用于返回当前地理位置的纬度坐标,而initialize_map()
函数用于绘制地图并接受可选的预定义坐标,否则,请使用默认的随机坐标.
As you can see, I intend to make separate functions for google map features. The locate_self()
function is used to return latlng coordinates of current geolocation while the initialize_map()
function draws the map and accept optional predefined coordinated otherwise, use a default random coordinates.
问题在于,initialize_map()
的发射速度比locate_self()
快,将返回的元素渲染为undefined
,最后,initialize_map()
使用默认坐标.
The problem is, initialize_map()
fired faster than locate_self()
, rendering the returned element as undefined
and finally, initialize_map()
goes with default coordinate.
在locate_self()
内,我给出一个alert()
以及当前的地理位置坐标来创建一个测试块,以指示此功能正常工作.
Inside locate_self()
, I created a test block by giving an alert()
, along with current geolocation coordinates to indicates that this function is working properly.
问题是我如何让initialize_map()
等待等待locate_self(),直到它返回坐标而不是undefined
?
The question is how do I make initialize_map()
wait for locate_self() until it returns the coordinate rather than undefined
?
我稍后将对接收latlng并返回地址字符串的函数使用相同的解决方案. Geocoder也具有相同的延迟".
I will use the same solution later for function that accept latlng and return address string. Geocoder also have the same kind of 'delay'.
我以前尝试过使用超时,但是它仍然给我未定义的(也许我不知道放置超时块,我不知道).
I tried using timeout before but it still giving me undefined (maybe I was wrong placing the timeout block, I don't know).
谢谢,如果这是转贴,我感到非常抱歉
Thanks and I'm very sorry if this is a repost
推荐答案
地理位置服务是异步的.解决此问题的最简单方法是使用回调而不是使用return
:
The geolocation service is asynchronous. The simplest way around this is to use a callback instead of using return
:
function initialize_map(result) {
if (result !== 'error') {
gm_map = new google.maps.Map(gm_map_container, gm_map_options);
if (!result) {
result = new google.maps.LatLng(-34.397, 150.644);
}
gm_map.setCenter(result);
}
}
function locate_self(callback) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
callback(pos);
});
} else { callback('error'); }
}
locate_self(initialize_map);
演示.
这篇关于Google Map同步地址解析延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!