M.Dos M.Dos - 26 days ago 7
jQuery Question

Execute event on first click only

I’m trying to execute the below click(function) only on first click, but it always executes whenever I click on the map.
Is it possible to use One-Click with the below code ? Thanks in advance

var placedMarkers = 0;
var availableMarkersToPlace = 1;
setTimeout( function(){
if(placedMarkers >= availableMarkersToPlace)
return;
placedMarkers++;
var map = Appery("google_map").gmap;
google.maps.event.addListener(map, 'click', function(event) {
localStorage.setItem('selectedLat', event.latLng.lat());
localStorage.setItem('selectedLng', event.latLng.lng());
placeMarker(event.latLng,map);
alert(event.latLng);
});

}, 1000);

Answer

Just create flag-value, which will decide, run your function or skip:

var placedMarkers = 0;
var availableMarkersToPlace = 1;
var clicked = false;

setTimeout( function(){
    if(placedMarkers >= availableMarkersToPlace)
        return;
    placedMarkers++;
    var map = Appery("google_map").gmap;
    google.maps.event.addListener(map, 'click', function(event) { 
        if(!clicked) {
            clicked = true;
            localStorage.setItem('selectedLat', event.latLng.lat());
            localStorage.setItem('selectedLng', event.latLng.lng()); 
            placeMarker(event.latLng,map);  
            alert(event.latLng);            
        }

    });

}, 1000);