删除标记 - Google Maps Javascript API v3

时间:2014-04-21 15:55:39

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

尝试使用Maps API。我被困在去除标记。 添加标记效果很好,但删除不起作用。 知道为什么这不起作用吗?提前谢谢!

function placeMarker(event) {
    var marker = new google.maps.Marker({
      clickable: true,
      position: event.latLng,
      map: map
    });
  }

  function deleteMarker() {
    marker.setMap(null);
    marker = null;
  }

   function initialize() {
    var mapOptions = {
      zoom: 8,
      center: home
    };
    map = new google.maps.Map(document.getElementById('map-canvas'),
        mapOptions);

    google.maps.event.addListener(map,'rightclick', placeMarker);
    google.maps.event.addListener(marker,'click', deleteMarker);
  }

  google.maps.event.addDomListener(window, 'load', initialize);

1 个答案:

答案 0 :(得分:1)

定义全局变量

var map,
    marker,
    home = new google.maps.LatLng(46.5, 13.5);

导致错误消息:

Uncaught TypeError: Cannot read property '__e3_' of undefined      main.js:15

来自

google.maps.event.addListener(marker, 'click', deleteMarker);

marker仍然是undefined,因为它未创建,并且无法将事件侦听器附加到它。该行必须移至placeMarker()函数:

function placeMarker(event) {
    marker = new google.maps.Marker({
        clickable: true,
        position: event.latLng,
        map: map
    });

    google.maps.event.addListener(marker, 'click', deleteMarker);
}

请参阅example at jsbin