Reputation: 10227
When I add a slew of Pushpins
to a Bing Map, I want the zoom level to automagically update to the "best fit" - the "closest in" view that allows all of the Pushpins to be displayed.
I would imagine that it would be done by computing the zoom level required by discovering the latitude values that are the furthest north and southmost, and the longitude values that are furthest east and west, and then centering on the average value of those.
My idea is passing a List of GeoCoordinates
to a method that would return the appropriate ZoomLevel, and possibly a separate method that would calculate the center point of the map.
These two values could then be used for the map's SetView(location, ZoomLevel)
method.
Has this been done already, or is there a Bing Maps call that will handle this?
Upvotes: 1
Views: 810
Reputation: 125197
There is an overload of SetView which accepts a list of locations and set the view to the bounding rectangle of those locations. It ensures all the locations are visible; you also need to add a bit of extra margins to the view rectangle to make sure all the pushpins are visible.
Having pushpins on the map, means you already have a list of locations or if you don't have you can easily get the locations of all those pushpins.
Example
Assuming you have followed the steps on How can I add a Bing Maps Component to my C# Winforms app?, add a button to the form and handle its click event like this:
private void button1_Click(object sender, EventArgs e)
{
var map = this.userControl11.myMap;
//Locations
var locations = new[] {
new Location(47.6424, -122.3219),
new Location(47.8424, -122.1747),
new Location(47.67856, -122.130994)};
//Add Pushpins
locations.Select(x => new Pushpin() { Location = x })
.ToList().ForEach(x => { map.Children.Add(x); });
//Margin
var w = new Pushpin().Width;
var h = new Pushpin().Height;
var margin = new Thickness(w / 2, h, w / 2, 0);
//Set view
map.SetView(locations, margin, 0);
}
And this is the result:
Note: If you don't have the list of locations, but you have just a few pushpins on the map, then you can easily get locations like this:
var map = this.userControl11.myMap;
var locations = map.Children.OfType<Pushpin>().Select(x => x.Location);
Upvotes: 3