Understanding Geocoding in Javascript

Ok, I have a google map setup in jQuery app. (V3). I can geocode maps all day long.

So, I thought I would be smart, and move the actual geocoding function, well, as well as the function.

Here is the function I'm using:

    function geocode (address) {
        var self = this;
        geocoder.geocode ({'address': address}, function (results, status) {
            console.log (status);
            if (status == google.maps.GeocoderStatus.OK) {
                return results [0] .geometry.location;
            } else {return null; }
        });
        return "WTF?";
    }

"WTF" is a joke that you will see in an instant.

Now, later in my code, I am trying to call a function as follows:

var start_latlng;
start_latlng = geocode (start_address);

console.log (start_latlng);

What I get in the console:

WTF?
Ok

Note that “WTF” is before “OK,” although I type “OK” inside the function. (console.log (status))

My guess is that it takes a little time for geocoding to return, and the function continues until the first geocoded value is returned.

Does anyone have any suggestions for improving this so that my "start_latlng" contains the expected values?

Thanks for any pointers.

* EDIT **

Here is what I ended up doing.

I call the function as follows:

        geocode (start_address, function (data) {
            start_latlng = data;
            console.log (start_latlng);          
        });

And here is a new feature (not over, but you get the point)

    function geocode (address, callback) {
        geocoder.geocode( { 'address': address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                callback(results[0].geometry.location);
            }
            else {
                callback("Error");
            }
        });
    }

.: -)

.

+3
2

, geocode() , . , , , , , return.

function geocode(address) {
    geocoder.geocode( { 'address': address }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            /* do whatever you need to do with the results here */
        }
        else {
            /* handle the error */
        }
    });
}
+3

, , , . , , , - .

+1

Source: https://habr.com/ru/post/1777670/


All Articles