我需要在地图上放置多个标记,并能够点击它们。然后应该在我的网站中启动某个JS,为此我使用以下代码:
function initialize() {
geocoder = new google.maps.Geocoder();
var mapCanvas = document.getElementById('map_canvas');
var mapOptions = {
center: new google.maps.LatLng(64.113598, -21.8569031),
zoom: 12,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions)
function getAddress (address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
return;
}
});
}
getAddress("some address here");
}
google.maps.event.addListener(marker, 'click', function() {
map.setZoom(8);
});
google.maps.event.addDomListener(window, 'load', initialize);
但是这给了我Uncaught ReferenceError: marker is not defined
错误。我做错了什么?
答案 0 :(得分:2)
您已在函数var marker
中定义了getAddress
,因此此变量仅在此范围内可用。请将变量定义移到getAddress
之外,如下所示:
var marker;
function initialize() {
// ...
function getAddress (address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
return;
}
});
}
getAddress("some address here");
}