Pages

Sunday, July 15, 2012

Getting Bounds of an EntityCollection object.


Today I discovered that the Bing Maps 7 EntityCollection class does not have a getBounds() method.  This is slightly annoying if you want to re-center the map to the bounds of a layer's pushpins for example.

It really doesn't take very much to get a LocationRect object that can be used with Map.setView() though. Here's how I did it:

function getECbounds(ec) {
    var locations = [];
    var len = ec.getLength();
    for (var i=0;i<len;i++) {
        locations.push(ec.get(i).getLocation());
    }
    return Microsoft.Maps.LocationRect.fromLocations(locations);
}

From there, all it takes is a single line to adjust the map view to your new LocationRect:

map.setView({bounds:getECbounds(map.entities)});

Keep in mind this will only work with entities that have a getLocation() method (IE: Infoboxes and Pushpins.)

That's all.

No comments: