How to zoom a bing map to display a set of lat/long points?
Asked Answered
C

2

5

I'm using the Bing Maps v7 control.

I have an array of latitude/longitude points. (of type Microsoft.Map.Location)

From that array, I can generate a rectangle, and a center of the rectangle, using LocationRect.fromLocations()

When creating a map with the Map constructor, I can center the map using the center of that rectangle. It looks something like this:

    var LLA = [
       new Microsoft.Maps.Location(43.386,-111.6123),
       new Microsoft.Maps.Location(43.4929, -112.0349),
       new Microsoft.Maps.Location(43.2609,-115.7811),
       ...
    ];
    var r = Microsoft.Maps.LocationRect.fromLocations(LLA);
    var mapOptions = {
        credentials : bingMapsKey,
        center      : r.center,
        mapTypeId   : Microsoft.Maps.MapTypeId.road,
        zoom        : 7
    },
    elt = document.getElementById('out2');
    var map = new Microsoft.Maps.Map(elt, mapOptions);

That works, and the map that gets created is centered around those points. How can I set the zoom level of the Bing Map so that it displays the entire rectangle?

See here: http://jsfiddle.net/MQ76x/

Cismontane answered 17/10, 2011 at 18:36 Comment(0)
T
8

Forget passing center/zoom, and pass the rectangle as bounds instead:

var mapOptions = {
  credentials : bingMapsKey,
  bounds      : r, // <-- HERE
  mapTypeId   : Microsoft.Maps.MapTypeId.road
}
Trill answered 19/10, 2011 at 14:20 Comment(0)
S
0

For anyone landing here as me and searching for a calculation for the zoom for BingMaps V8 depending on the center of a location (latitude, longitude) and the radius of the location in kilometers:

(Maybe you are also drawing a circle with the Microsoft.Maps.SpatialMath at the center of the location)

function getZoomLevel(radiusInKilometer: number, latitude: number, heightOfMapInPixels: number, widthOfMapInPixels: number): number {
    const rangeInMeters = radiusInKilometer * 1000;
    // we take the lower value of the bounding rect of the map, so the circle will be best seen
    const limitBoundPixels = Math.min(heightOfMapInPixels, widthOfMapInPixels);
    const zoom = Math.floor(Math.log(156543.03392 * Math.cos(latitude * Math.PI / 180) / (rangeInMeters / limitBoundPixels)) / Math.log(2));

    return zoom;
}
Sieve answered 7/6, 2018 at 13:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.