Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

google maps - GoogleMaps v3 API Create only 1 marker on click

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 more than once I would like it to move the existing marker to the new position Can anyone help here is the code

 function placeMarker(location) {
        var clickedLocation = new google.maps.LatLng(location);
        var marker = new google.maps.Marker({
            position: location,
            map: map
        });
    }

google.maps.event.addListener(map, 'click', function(event) {
        placeMarker(event.latLng);
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...