Search code examples
javascriptgoogle-maps-api-3global-variablesgoogle-geocoder

getting latLong from google geocoding api


I am trying to use the Google Geocoding API to get the latitude and longitude from the address.I want to store the coordinates inside a variable to use them later on.I know it is a asynchronous call.In the code below I try to use the function useCordinates to assign the coordinates to a global variable so that I can use it later on.But I am getting cordinates is not defined when I debug.I am new to javascript.I read somewhere that implied global variables do not need to be defined.

myGlobalVar = 'Hello world'; Thanks for the help.

 function codeAddress(address){
  var loc=[];
  geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
     // no need to define it in outer function now
    loc[0]=results[0].geometry.location.lat();
    loc[1]=results[0].geometry.location.lng();

    useCordinates( loc ); 

  } else {
    alert("Geocode was not successful for the following reason: " + status);
  }
});
}

function useCordinates(cordinateArray){
 cordinates= cordinateArray;
  }
functionTestCodeAddress(){
 start = document.getElementById('start').value;
 codeAddress(start);
 //assign the global variable 'cordinates'
 document.getElementById('start').value=cordinates; 
}

Solution

  • The problem is not the variable, the problem is when you try to access the variable.

    Currently you do it inside TestCodeAddress() immediately after the call of codeAddress(), that's to early because the asynchronous request has not been finished yet at this time.

    You may e.g. move this line:

    document.getElementById('start').value=cordinates; 
    

    into useCordinates()