如何使用LocationCollection在WP7 Bing Maps控件中缩放以适应屏幕?

8
如何在Windows Phone 7上将Microsoft.Phone.Controls.Maps.Map控件缩放到正确的缩放级别?
我有一个GeoCoordinates的LocationCollection,并且我自己计算了中心点,但现在要如何计算正确的缩放级别以适应LocationCollection?
附言:是否有开箱即用的方法来计算GeoCoordinates的中心点,以免我自己计算?
编辑: 我找到了另一个很好的解决方案:http://4mkmobile.com/2010/09/quick-tip-position-a-map-based-on-a-collection-of-pushpins/ map.SetView(LocationRect.CreateLocationRect(points));
3个回答

8
您可以使用以下代码计算包含一组点的LocationRect,然后将LocationRect传递给地图控件上的SetView()方法:
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);

地图控件处理从当前位置到新位置的动画。

注意:您需要使用System.LinqMinMax方法,因此需要添加using语句。


是的,这就是我做的方式。效果很好。 - Chris Rae
3
谢谢,我会接受你的答案,但是我已经找到了另一个好的解决方案:map.SetView(LocationRect.CreateLocationRect(points)); // http://4mkmobile.com/2010/09/quick-tip-position-a-map-based-on-a-collection-of-pushpins/ (该代码能够根据一组图钉位置自动调整地图视角,详见链接) - Buju
谢谢。很高兴你找到了解决方案。我得记住LocationRect比我想象的更有帮助 :) - Derek Lakin
1
这是一个不错的解决方案,但请注意,如果您的点位于180经线附近,此代码将无法正常工作。您将得到一个横跨整个世界宽度的矩形... - Ran
2
如果有人和我一样有点困惑,它在Windows Phone 8中被称为LocationRectangle :) - robertk

1
Derek已经给出了答案,所以你应该接受他的答案。我提供了一种替代代码,适用于有许多点的情况。这种方法只迭代一次点集合,而不是4次,但它不如美观。
 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));

+1...我不认为这是过早的优化;我会称接受的答案为过早的退化 :-) - Ben M

0

根据其他答案的建议,我使用SetViewLocationRect

然而,我发现它总是产生太低的缩放级别,因为只使用整数值。例如,如果完美的缩放级别是5.5,则会得到5.0。为了获得适当的匹配,我从TargetZoomLevelTargetBoundingRectangle计算一个新的缩放级别:

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

这个例子将缩放级别设置为适合屏幕上viewRect的高度。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接