Search code examples
javascriptloopsgoogle-maps-api-3google-geocoder

Prevent Looping Inside Geocoder Google Maps API


I'm using Google Map API. I want to get lat and long with a given address. I did this

var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': 'Stockholm' }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var latitude = results[0].geometry.location.nb;
            var longitude = results[0].geometry.location.ob;
            console.log(latitude);
        }
});

However i get that console log run repeatedly. I just want to have it running once, but i didn't find any idea.


Solution

  • Declare a new variable that shows whether the geocoding has been called, and change it to true the first time this happens.

    var geoCalled = false;
    
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': 'Stockholm' }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var latitude = results[0].geometry.location.nb;
        var longitude = results[0].geometry.location.ob;
        if (!geoCalled) {
          console.log(latitude);
          geoCalled = true;
        }
      }
    });