谷歌地图标记不是递增数组

Google Maps markers not incrementing array

本文关键字:数组 地图 图标 谷歌      更新时间:2023-09-26

我找遍了,但找不到答案。我有一个地图,当我点击时,它会在我点击的地方添加标记。我将这些标记推入数组,但当我做一个标记时,似乎覆盖了之前在数组中的标记,而不是向数组添加另一个索引。无论地图上有多少标记,数组总是像这样。下面是代码

addLatLng: function(event) {
    var path = this.poly.getPath();
    var markers = [];
    path.push(event.latLng);
    this.calcDistance(path);
    var marker = new google.maps.Marker({
      position: event.latLng,
      title: '#' + path.getLength(),
      map: this.map
    });
    markers.push(marker);
    console.log(markers);
    console.log(marker);
    // debugger;
    function removeMarkers(map) {
      for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(map);
      }
      markers = [];
    }
    $('#btn-clear-map').on('click', function(event) {
      event.preventDefault();
      removeMarkers(null);
    });
    $('#btn-clear-point').on('click', function(event) {
      event.preventDefault();
      markers[markers.length -1].setMap(null);
    });
  },

这是骨干视图的一部分,如果有区别的话。我只是不知道为什么当我推一个标记时,它似乎覆盖了已经在那里的标记。

编辑:好吧,我刚刚明白了为什么,每次我点击做一个新的标记,它是重置标记数组。有什么聪明的方法可以绕过这个问题吗?

问题是您在每次调用addLatLng方法时都重新声明markers数组(您也是新的事件处理程序并每次创建removeMarkers函数和闭包)

相反,您应该将标记数组保留为视图的属性,如下所示:
Backbone.View.extend({
  initialize: function() {
    this.markers = [];
  },
  events: {
    'click #btn-clear-map': 'removeMarkers',
    'click #btn-clear-point': 'clearPoint',
  },
  render: function() {},
  addLatLng: function(event) {
    var path = this.poly.getPath();
    path.push(event.latLng);
    this.calcDistance(path);
    var marker = new google.maps.Marker({
      position: event.latLng,
      title: '#' + path.getLength(),
      map: this.map
    });
    this.markers.push(marker);
  },
  removeMarkers: function(event) {
    event.preventDefault();
    for (var i = 0; i < this.markers.length; i++) {
      this.markers[i].setMap(null);
    }
    this.markers = [];
  },
  clearPoint: function(event) {
    event.preventDefault();
    this.markers[this.markers.length - 1].setMap(null);
  }
});