我刚刚开始使用谷歌地图API的新体验。 我想知道它是如何工作的,我通常在论坛上理解或找到我的答案。
我遇到了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);
}
如果你能看一下,那就太好了。
答案 0 :(得分:1)
setCenter()
失败时,infowindow未打开。这是由于geocoder.geocode()
函数中使用的showQrcodes
调用的异同性质。函数setZoom()
和setCenter()
以及infowindow的开放必须在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);
}