0

I'm trying to use this function to geocode a string passed to it into a google maps result.

function codeAddress(address) {
       var firstResult;
       geocoder.geocode( { 'address': address}, function(results, status) {
         if(status == google.maps.GeocoderStatus.OK) {
             firstResult = results[0];
           } else {
             firstResult = "failed";
         }
       });
       return firstResult;
     }

The problem is that when I try to debug it using the debugger from chrome and insert a breakpoint outside and inside the ceocoder.geocode statement, I can clearly see the program execution go at the third line, but it skips the inner lines and goes straight to the return value (returning an undefined value). Some other times, it goes through the if statement within it, but it doesn't go to the return statement although I have set up a breakpoint there.

Am I trying to do this the wrong way? How can I fix this?

user2565010
  • 1,876
  • 4
  • 23
  • 37

1 Answers1

0

I found some possible answers on StackOverflow, they might help:

Aleem Saadullah on SO posted:

Finally figured it out. It was a silly error. I had linked my Javascript file before linking the jQuery. The code works fine now.

Mikko Ohtamaa answered on SO:

To be strict, whatever custom CGI you are using does not conform JavaScript syntax.

What I suggest is that you make your custom dynamic processing into JavaScript comments, so that it doesn't affect the normal JavaScript parsing. This is much easier than writing your custom JavaScript parser to cater your custom syntax.

E.g.

// %import and other custom commands here

The best approach is that you would not put any non-JavaScript to JS files at all. If you need importing and such there are some more generic JavaScript solutions for them.

http://browserify.org/

http://requirejs.org/

EDIT 2:

Found an answer on Engineer's answer on SO:

geocoder.geocode works asynchronously, so you need to wait until its response will be delivered from google's servers, and only then use responded data. Put your loop inside of callback:

geocoder.geocode( { 'address': zip }, function(results, status) { // status is empty
  if (status == google.maps.GeocoderStatus.OK) {
     var userLat = results[0].geometry.location.lat();
     var userLng = results[0].geometry.location.lng();
     userLatLng = results[0].geometry.location;
     for (var i = data.length-1; i--;) { 
        //loop body
     }
}});//end geocode
Community
  • 1
  • 1
user1420563
  • 195
  • 1
  • 12