質問

I am attempting to use the MapQuest Geocoding Module within the JavaScript API to dynamically batch geocode addresses:

MQA.withModule('geocoder', function() {

    var addresses = new Array();

    $.getJSON('get_marker_json.php', function( data ) {

        $.each(data, function(i, item) {
            addresses.push(street: item.address, city: item.city, state: item.state, postalCode: item.zip);
        });

    });

    /*Pass an array of locations to be geocoded and placed on map*/
    map.geocodeAndAddLocations(

        // add addresses from array here
        addresses

    );

});

This does not work however. It seems that the addresses must be pre-defined. For example:

map.geocodeAndAddLocations([
            'Littleton CO',
            { city: 'Steamboat Springs', state: 'CO' },
            { street: '555 17th St', postalCode: '80202' },
            'Winter Park CO'
        ]);

How might I achieve this?

Thanks!

役に立ちましたか?

解決

The getJSON() call is asynchronous, meaning map.geocodeAndAddLocations() is being run while the network request is still out, and addresses is empty.

Move your call to map.geocodeAndAddLocations() into the callback in getJSON() after assembling the addresses array. (Also, why are you assembling an array of JSON strings?)

他のヒント

you can also make the getJSON() call synchronous by adding the following beforehand and make it wait until array is filled:

$.ajaxSetup({'async': false});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top