开发者

Get results from Google geocoder into an array?

开发者 https://www.devze.com 2023-03-28 05:47 出处:网络
I have the following code: var data = geocoder.geocode({\'address\': \'new york\'}, function (results, status)

I have the following code:

var data = geocoder.geocode({'address': 'new york'}, function (results, status)
{
    if(status == google.maps.GeocoderStatus.OK)
    {
        response($.map(results, function(item) 
        {
            retur开发者_开发技巧n
            {
                value: item.formatted_address
            }
        }));
    }
});

I need to get the output of the data to look like this:

var data = [
    {value: 'some1'},
    {value: 'some2'},
    {value: 'some3'}
];

I really don't have a clue what Im doing to get it into that state and I'm not sure what exactly is returned by the initial geocoder request. The info on the google code website was rather limited when it came to explaining the above function.

Any idea how I can do it? Thanks.


Geocoder.geocode() does not return any values, so you CANNOT do:

var data = geocoder.geocode({'address': 'new york'}, function (results, status) {

Moreover, the callback function (results, status) {...} that you specify in the above call is called asynchronously by the geocoder when it finished the geocoding. So, you need to use the results in the callback itself, e.g. filling some textbox etc. Here is a template using pure Javascript, you can adapt it to your JS framework appropriately:

geocoder.geocode({'address': 'new york'}, 
    function (results, status) {     
        if(status == google.maps.GeocoderStatus.OK) {
            for (var i = 0; i < results.length; ++i) {         
                alert(i + ": " + results[i].formatted_address);
            }             
        }         
    }
);     


.map returns a jQuery object. To get the regular array, use get

var data = $.map(results, function(item) {
    return { value: item.formatted_address };
    }).get();
0

精彩评论

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