Search code examples
javascriptgeocodingmapquest

Dynamically add addresses to MapQuest JavaScript Geocode Module


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!


Solution

  • 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?)