Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

set marker google maps javascript api

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());
      }

    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...