-1

Please help me resolve this problem.
I want to get address from latitude, longitude in Google Maps. Here is my functions:

function codeLatLng() {
var geocoder = new google.maps.Geocoder();
var lati = document.getElementById("latitude_value").value;
var lngi = document.getElementById("longitude_value").value;
var latlng = new google.maps.LatLng(lati, lngi);
var infowindow = new google.maps.InfoWindow();
var ngo;
geocoder.geocode({'latLng': latlng}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    if (results[1]) {
      map.setZoom(11);
      marker = new google.maps.Marker({
        position: latlng,
        map: map
      });
      ngo = results[1].formatted_address;
      infowindow.setContent(results[1].formatted_address);
      infowindow.open(map, marker);
    }
  } else {
    alert("Geocoder failed due to: " + status);
  }
});
return ngo;
 }

When this function is executed. The address is displayed in Maps.
However, this is not what I need. I just want to assign this address to variable 'ngo' as a string.
This function return 'ngo' which is displayed in the text field as 'undefinded'.
I need some help to solved this problem.
Thanks.

Ngo Van
  • 857
  • 1
  • 21
  • 37

2 Answers2

1

I just want to assign this address to variable 'ngo' as a string.

That's the problem right there. You can't do that. JavaScript just doesn't work that way. The geocoder call is asynchronous. It returns before the data is received from the server. The data isn't ready until the geocoder callback function is called.

What you need to do instead is to use that ngo data in the callback function itself, or call another function and pass it the data, and use the data there.

For example, where you have this line:

ngo = results[1].formatted_address;

you can replace it with:

useNGO( results[1].formatted_address );

where useNGO is a function you've defined (anywhere) like this:

function useNGO( ngo ) {
    // Do stuff with ngo here
}
Michael Geary
  • 28,450
  • 9
  • 65
  • 75
0

I believe your problem is that using the var keyword when declaring var ngo makes ngo a local variable, so it doesn't exist outside of codeLatLng(). Try deleting var ngo, placing ngo = ""; somewhere outside of any function declarations (like right before function codeLatLng() {), and let me know if that works :)

asifrc
  • 5,781
  • 2
  • 18
  • 22
  • I try it! But It not work. The problem is I don't really know the way geocoder execute. Anyway, thanks for your help. – Ngo Van Apr 15 '13 at 09:55
  • can you put `console.log(results[1].formatted_address);` right before `ngo = results[1].formatted_address;` and see what the console says? – asifrc Apr 15 '13 at 09:58