GoogleMaps v3 API Create only 1 marker on click

后端 未结 5 2041
孤城傲影
孤城傲影 2020-12-01 10:30

I am successfully creating a marker on click however, using the following code, I get a new marker with every click, I only ever want one marker added and if someone clicks

5条回答
  •  醉酒成梦
    2020-12-01 10:58

    var marker;
    
    function placeMarker(location) {
      if ( marker ) {
        marker.setPosition(location);
      } else {
        marker = new google.maps.Marker({
          position: location,
          map: map
        });
      }
    }
    
    google.maps.event.addListener(map, 'click', function(event) {
      placeMarker(event.latLng);
    });
    

    You have to work on the same marker all the time - do not create new ones. Here you have a global variable marker and in placeMarker function you assign marker to this variable first time. Next time it checks that marker exists already and then just changes its position.

提交回复
热议问题