我刚刚开始一个新的经验谷歌地图API。我试图了解它是如何工作的,我通常理解或找到我的答案在论坛上。
我和setCenter的财产有问题,我找不到我的错误.在点击一个标记,它应该setCenter到标记和放大。setCenter并不总是工作,有时,它在几公里外的setCenter .
这是我的代码:
var user;
var pos;
// Try HTML5 geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Show user marker
user = new google.maps.Marker({
position: pos,
title: 'My location',
icon: iconUser,
map: map,
zIndex: google.maps.Marker.MAX_ZINDEX + 1
});
map.setCenter(pos);
// Get address
geocoder.geocode({
"latLng": pos
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
infowindow.setContent('<b>Here you are :</b><br />' + results[0].formatted_address);
infowindow.open(map, user);
// Show infowindow user marker click
google.maps.event.addListener(user, 'click', function () {
infowindow.open(null, null);
infowindow.setContent('<b>Here you are :</b><br />' + results[0].formatted_address);
infowindow.open(map, user);
map.setZoom(15);
map.setCenter("latLng");
});
// Hide infowindow map click
google.maps.event.addListener(map, 'click', function () {
if (infowindow) {
infowindow.open(null, null);
}
});
} else {
alert('Cannot determine address at this location.');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}, function () {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}如果你能看一看,那就太好了。
发布于 2014-02-09 13:00:06
当setCenter()失败时,不打开is。这是由于在geocoder.geocode()函数中使用的showQrcodes调用的异步性质。在成功的setZoom()函数和setCenter()函数中,必须调用geocode()函数和信息库的开放函数。
我会将for循环在showQrcodes()函数中更改为:
for (var i = 0; i <= locationArray.length - 1; i++) {
coords = new google.maps.LatLng(locationArray[i][1], locationArray[i][2]);
(function(i) {
var marker = new google.maps.Marker({
position: coords,
title: locationArray[i][0],
map: map,
icon: iconQr
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function () {
console.log('showQrcodes marker onclick event listener');
console.log(marker);
infowindow.open(null, null);
title = this.title;
geocoder.geocode({
latLng: this.position
}, function (responses) {
if (responses && responses.length > 0) {
infowindow.setContent('<b>' + title + ' : </b><br />' + responses[0].formatted_address);
map.setZoom(15);
map.setCenter(marker.getPosition());
infowindow.open(map, marker);
} else {
infowindow.setContent('Cannot determine address at this location.');
}
});
});
})(i);
}https://stackoverflow.com/questions/21651460
复制相似问题