【发布时间】:2014-03-25 11:20:40
【问题描述】:
我正在学习 google map API,当我尝试将当前坐标添加到数组时遇到了这个问题。这是我的代码:
var locations = [];
在 initialize() 中我有:
function initialize() {
infowindow = new google.maps.InfoWindow();
var myOptions = {
zoom: 10,
mapTypeControl: true,
navigationControl: true,
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
add_location('Place 1', 37.2846372, -123.3270422);
set_current_location();
set_markers(new google.maps.LatLngBounds(), map);
}
第一个标记已设置,而 set_current_location() 似乎不起作用。以下是其余代码:
// add new location to the locations array
function add_location(description, lastitude, longtitude) {
locations.push([description, lastitude, longtitude]);
}
// Set all the markers in the location arrays and bound/frame the map
function set_markers(bounds, map) {
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
}
// Get current location based on the IP Address
function set_current_location() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
add_location('My location', position.coords.latitude, position.coords.longitude);
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
谁能帮助或给我一个提示?我想将当前位置添加到位置数组中,这样我就可以跟踪我添加了多少位置。非常感谢。
【问题讨论】:
-
在
getCurrentPosition的回调结束时调用set_markers,而不是在initialize中。检索用户位置是一个异步过程,初始化完成后结果尚不可用。 -
我同意莫勒博士的观点。我看到了同样的事情。 getCurrentPosition() 是在后台执行的异步调用,因此在上面的代码中不能保证当 set_markers() 被调用时 getCurrentPosition() 已经完成。将 set_markers() 调用放在 getCurrentPosition() 的末尾将保证用户的地理位置将在标记放置在地图上之前完成。
标签: javascript google-maps google-maps-api-3 geolocation