How to zoom to fit in WP7 Bing Maps control using LocationCollection?

假如想象 提交于 2019-12-04 03:41:15

You can use the following code to calculate the LocationRect that bounds a set of points, and then pass the LocationRect to the SetView() method on the map control:

var bounds = new LocationRect(
    points.Max((p) => p.Latitude),
    points.Min((p) => p.Longitude),
    points.Min((p) => p.Latitude),
    points.Max((p) => p.Longitude));
map.SetView(bounds);

The map control handles animating from the current position to the new location.

NOTE: You'll need a using statement for System.Linq to get the Min and Max methods.

Derek has already given the answer so you should accept his, I offer an alternative code for cases where there many points. This approach only iterates the points collection once instead 4 times however it isn't as asthetically pleasing.

 double north, west, south, west;

 north = south = points[0].Latitude;
 west = east = points[0].Longitude;

 foreach (var p in points.Skip(1))
 {
     if (north < p.Latitude) north = p.Latitude;
     if (west > p.Longitude) west = p.Longitude;
     if (south > p.Latitude) south = p.Latitude;
     if (east < p.Longitude) east = p.Longitude
 }
 map.SetView(new LocationRect(north, west, south, east));

As suggested by the other answers I use SetView with a LocationRect.

However I found that it always produces to low zoom level, since only integer values was used. If for instance the perfect zoom level would be 5.5, you would get 5.0. To get a proper fit I calculate a new zoom level from TargetZoomLeveland TargetBoundingRectangle:

viewRect = LocationRect.CreateLocationRect(coordinates);
map.SetView(viewRect);
double scale = map.TargetBoundingRectangle.Height/viewRect.Height;
map.ZoomLevel = map.TargetZoomLevel + Math.Log(scale, 2);

This example sets the zoom level to fit viewRect's height on the screen.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!