谷歌地图api标记未定义错误

时间:2015-04-14 05:41:21

标签: javascript google-maps google-maps-api-3

我需要在地图上放置多个标记,并能够点击它们。然后应该在我的网站中启动某个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错误。我做错了什么?

1 个答案:

答案 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");
}