Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
在WP8,地图控件经过了修整,新的Map API 在Microsoft.Phone.Maps.Controls 命名空间下,而原来的BingMap control (在Microsoft.Phone.Controls.Maps命名空间,注意区别)已经不再推荐使用了。
这个CASE的需求非常简单,假设我们当前地图中的内容正在移动的时候,触发某些事件或者显示某些提示,而在停止移动之后,继而有另外一种提示,也就是需要找到一种方法,在WP8中,检测到当前地图正在移动或者停止移动。
我们的研究从Microsoft.Phone.Maps.Controls.Map 对象的若干个事件入手,但是发现都没有现成的能够满足我们要求的对象。诸如CenterChanged, ViewChanged,ZoomLevelChanged这些事件,也是只在某些如Center、ZoomLevel的相关属性变动时才会触发,但是并不能直接告诉我们当前地图正在移动或停止。
我们的解决方案是在CenterChanged事件中,加入一个DispatcherTimer,这个timer每间隔一定事件就进行检测,并和前一次timer触发时center有所改变而记录下的时间来进行比较,判断当前地图是否正在移动。代码实现如下:
1: DateTime lastCenterChangeTime = DateTime.Now;
2:
3: bool isChanging = false; //这里完全也可以设定成一个实现INotifyPropertyChanged的ViewModel的通知属性,这样一旦属性值改变了,就可以通过绑定反馈到视图页面
4:
5:
6:
7: private DispatcherTimer notifyCenterChangedTimer;
8: const int timerInterval = 100; //timer的执行间隔
9: const int changeMinInterval =300;//最小触发地图位置变动的时间间隔
10:
11: private void sampleMap_CenterChanged(object sender, MapCenterChangedEventArgs e)
12:
13: {
14:
15: if (notifyCenterChangedTimer == null)
16:
17: {
18:
19: notifyCenterChangedTimer = new DispatcherTimer ();
20:
21: notifyCenterChangedTimer.Interval = TimeSpan.FromMilliseconds(timerInterval);
22:
23: notifyCenterChangedTimer.Tick += (timerSender, timerE) => {
24:
25:
26:
27: if ((DateTime.Now - lastCenterChangeTime).Milliseconds > changeMinInterval && isChanging == true)
28:
29: {
30:
31: isChanging = false;
32:
33:
34:
35: Debug.WriteLine("sampleMap_CenterChanged" + sampleMap.Center.ToString());
36: // 这里可以来调用实现定义的Event,实现事件驱动。
37:
38: }
39:
40: };
41:
42:
43:
44: notifyCenterChangedTimer.Start();
45:
46: }
47:
48:
49:
50:
51:
52: lastCenterChangeTime = DateTime.Now;
53:
54: isChanging = true;
55:
56: }
这里可以根据具体需求,加入Event,触发相关事件,或者把isChanging属性作为一个通知属性,实现PropertyChanged函数。
更多参考:
Maps and navigation for Windows Phone 8
https://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207045(v=vs.105).aspx
-Ranger