0
votes

I'm trying to make a call to the searchManager.geocode function and return the location object to be stored in an array.

I'm a javascript novice, so I expect this is probably a question more fundamental to javacript than to bing maps, but...

I'm experimenting with the Bing Maps search using this demo as my template: https://www.bing.com/api/maps/sdk/mapcontrol/isdk/searchbyaddress

Here is the example:

var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
    /* No need to set credentials if already passed in URL */
    center: new Microsoft.Maps.Location(47.624527, -122.355255),
    zoom: 8 });
Microsoft.Maps.loadModule('Microsoft.Maps.Search', function () {
    var searchManager = new Microsoft.Maps.Search.SearchManager(map);
    var requestOptions = {
        bounds: map.getBounds(),
        where: 'Seattle',
        callback: function (answer, userData) {
            map.setView({ bounds: answer.results[0].bestView });
            map.entities.push(new Microsoft.Maps.Pushpin(answer.results[0].location));
        }
    };
    searchManager.geocode(requestOptions);
});

What I would like to do is not actually do any work in the callback function, but simply return the location (`answer.results[0]') so that I can make a series of calls like this:

locations.push(geocodeAddress("address 1, city, state"));
locations.push(geocodeAddress("address 2, city, state"));

That locations array will be used for map bounds, adding pushpins, etc later.

1

1 Answers

0
votes

Since the geocode function is an async one, you can't ask it to immediately return something for later use. However, what you could do is pushing the location to array directly in the callback function:

var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
    /* No need to set credentials if already passed in URL */
    center: new Microsoft.Maps.Location(47.624527, -122.355255),
    zoom: 8 });
var locations = []; 
Microsoft.Maps.loadModule('Microsoft.Maps.Search', function () {
    var searchManager = new Microsoft.Maps.Search.SearchManager(map);
    var requestOptions = {
        bounds: map.getBounds(),
        where: 'Seattle',
        callback: function (answer, userData) {
            locations.push(answer.results[0].location);
        }
    };
    searchManager.geocode(requestOptions);
});

And your later calls would just be below since pushing to array is already taken care of:

geocodeAddress("address 1, city, state");
geocodeAddress("address 2, city, state");

Of course, you would still need some mechanism to keep track that all geocode calls are finished before using the locations array (perhaps through a counter in each callback). Also you would only need to load the Microsoft.Maps.Search module once despite repetitive usage.