删除所有显示的标记Google API

时间:2018-09-11 05:44:00

标签: javascript php laravel google-maps

我在Laravel项目中工作,并且如果我只选择1家商店,那么我具有用于显示和删除Google地图上所有商店的模块。

这是一个重复的问题,但是,为什么我的函数无法将功能showallmarks设置为null。

问题:一旦点击按钮,如何删除Google地图中显示的所有标记?

我在这里有代码。

显示所有标记:

showallmarks();

function showallmarks() {
  $.each(locations, function(index, value) {

    var position = new google.maps.LatLng(value.store_lat, value.store_long);
    var title = value.branch_name;
    var address = value.store_address;

    var contentString = "<h5>" + title + "</h5>" + address;

    var infowindow = new google.maps.InfoWindow({
      content: contentString
    });

    var marker = new google.maps.Marker({
      position: position,
      icon: google.maps.marker,
      map: map,
      zoom: 12
    });

    marker.addListener('click', function() {
      infowindow.open(map, marker);
    });
  });
}

单击此按钮后,showallmarks不得显示在Google地图上。

var markeronce;

$('button#addresses').click(function() {

  //removing all marks 
  showallmarks(null);

  var infowindow = new google.maps.InfoWindow({
    content: "<span>Visit us on our store.</span>"
  });
  var address_href = $(this).val();
  var commaPos = address_href.indexOf(',');
  var coordinatesLat = parseFloat(address_href.substring(0, commaPos));
  var coordinatesLong = parseFloat(address_href.substring(commaPos + 1, address_href.length));

  var centerPoint = new google.maps.LatLng(coordinatesLat, coordinatesLong);


  if (!markeronce) {
    markeronce = new google.maps.Marker({
      position: centerPoint,
      map: map,
      zoom: 8
    });
  } else {
    markeronce.setPosition(centerPoint);
  }
  map.setCenter(centerPoint);
})

Sample Image

1 个答案:

答案 0 :(得分:0)

添加按钮之类的

  <input type="button" value="Delete" onclick="DeleteMarkers()" />

并尝试使用此功能

    <script type="text/javascript">
    var markers = [];

    function DeleteMarkers() {
            //Loop through all the markers and remove
            for (var i = 0; i < markers.length; i++) {
                markers[i].setMap(null);
            }
            markers = [];
        };
    </script>