开发者

Understanding geocoding in Javascript

OK, I have Google maps setup in a jQuery app. (V3). I can geocode maps all day long.

So, I thought I'd be smart and move the actual geocode function into, well, a function.

Here is the function I am 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?";
    }

The "WTF" is a joke that you will see in a moment.

Now, later on in my code, I try to call the function like so:

var start_latlng;
start_latlng = geocode(start_address);

console.log(start_latlng);

What I get in the console is:

WTF?
OK

Notice the "WTF" is BEFORE the "OK" even though I print the "OK" within the function. (the console.log(status) )

My guess is because the geocoding needs a little time to return and the function continues on before returning the first geocoded value.

Does anyone have any suggestions on how to improve this so that my "start_latlng" contains the expected values?

Thanks for any pointers.

* EDIT **

Here is what I ended up doing.

开发者_C百科

I call the function like so:

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

And here is the new function (not finished but you get the idea)

    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");
            }
        });
    }

Works like a charm. :-)

Thanks for the tips and helping me think better.


What geocode() expects is a callback function as its argument. This means that the result of its call will be passed on to the function you specify when it's ready, asynchronously, and not as a return value.

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 */
        }
    });
}


The geocoder appears to be working asynchronously, so the result is not surprising. What I mean is, execution flows past the point of the geocoder invocation, thus the function returns and subsequently the geocoder returns its result - which is why you get the output in that order.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜