set marker google maps javascript api

扶醉桌前 提交于 2019-12-13 09:06:15

问题


I am trying to create with the google maps javascript api the following: After page loading a marker should become set at the users location, what now works. After that should where the user click on the map a marker become added and the previous one deleted. One marker should be only on the map. Now the previous marker wont become deleted and other become added what I dont want. What can I do to have always one marker on the map?

var markers = [];
    function initMap() {
      var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -34.397, lng: 150.644},
        zoom: 7
      });
      var infoWindow = new google.maps.InfoWindow({map: map});

      // Try HTML5 geolocation.
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          var pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
          };

          map.setCenter(pos);


      // This event listener will call addMarker() when the map is clicked.
      map.addListener('click', function(event) {
        deleteMarkers();
addMarkers(event.latLng);


      });
      addMarkers(pos);
      // Adds a marker to the map and push to the array.
      function addMarkers(location) {
      var marker = new google.maps.Marker({
        position: location,
        map: map
      });
      markers.push(marker);
    }
  // Sets the map on all markers in the array.
  function setMapOnAll(map) {
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(map);
  }
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
  setMapOnAll(null);
}


    // Deletes all markers in the array by removing references to them.
    function deleteMarkers() {
        clearMarkers();
      marker = [];
    }


        }, function() {
          handleLocationError(true, infoWindow, map.getCenter());
        });

      } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
      }

    }

回答1:


Take a look here I believe you are close :)

you are just setting your markers array to be nothing , but not actaully clearing the marker



来源:https://stackoverflow.com/questions/34597388/set-marker-google-maps-javascript-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!