Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); 
like image 212
rs82uk Avatar asked Sep 10 '10 11:09

rs82uk


People also ask

How many markers can Google Maps API handle?

2048 characters in URL is just under 100 GeoCode values. So, again no more than 100 markers.

How do I add multiple markers to Google Maps API?

Follow the below steps and add/show multiple markers on google maps using javascript with infowindows: Step 1 – Create HTML File For Display Multiple Markers. Step 2 – Add Google Maps API V3 in HTML. Step 3 – Implement JavaScript Function To Create Markers/Pins And Show on Google Map.

How do you customize a marker in maps?

For adding a custom marker to Google Maps navigate to the app > res > drawable > Right-Click on it > New > Vector Assets and select the icon which we have to show on your Map. You can change the color according to our requirements. After creating this icon now we will move towards adding this marker to our Map.


1 Answers

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.

like image 147
hsz Avatar answered Oct 05 '22 04:10

hsz