summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Maps.UWP/MapRenderer.cs
blob: f8a4c874138b32c456098ac4a50376f0f705992f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using Windows.Devices.Geolocation;
using Windows.UI;
using Windows.UI.Xaml.Controls.Maps;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;
#if WINDOWS_UWP
using Xamarin.Forms.Platform.UWP;

#else
using Xamarin.Forms.Platform.WinRT;

#endif

#if WINDOWS_UWP

namespace Xamarin.Forms.Maps.UWP
#else

namespace Xamarin.Forms.Maps.WinRT
#endif
{
	public class MapRenderer : ViewRenderer<Map, MapControl>
	{
		protected override async void OnElementChanged(ElementChangedEventArgs<Map> e)
		{
			base.OnElementChanged(e);

			if (e.OldElement != null)
			{
				var mapModel = e.OldElement;
				MessagingCenter.Unsubscribe<Map, MapSpan>(this, "MapMoveToRegion");
				((ObservableCollection<Pin>)mapModel.Pins).CollectionChanged -= OnCollectionChanged;
			}

			if (e.NewElement != null)
			{
				var mapModel = e.NewElement;

				if (Control == null)
				{
					SetNativeControl(new MapControl());
					Control.MapServiceToken = FormsMaps.AuthenticationToken;
					Control.ZoomLevelChanged += async (s, a) => await UpdateVisibleRegion();
					Control.CenterChanged += async (s, a) => await UpdateVisibleRegion();
				}

				MessagingCenter.Subscribe<Map, MapSpan>(this, "MapMoveToRegion", async (s, a) => await MoveToRegion(a), mapModel);

				UpdateMapType();
				UpdateHasScrollEnabled();
				UpdateHasZoomEnabled();

				((ObservableCollection<Pin>)mapModel.Pins).CollectionChanged += OnCollectionChanged;

				if (mapModel.Pins.Any())
					LoadPins();

				await UpdateIsShowingUser();
			}
		}

		protected override async void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			base.OnElementPropertyChanged(sender, e);

			if (e.PropertyName == Map.MapTypeProperty.PropertyName)
				UpdateMapType();
			else if (e.PropertyName == Map.IsShowingUserProperty.PropertyName)
				await UpdateIsShowingUser();
			else if (e.PropertyName == Map.HasScrollEnabledProperty.PropertyName)
				UpdateHasScrollEnabled();
			else if (e.PropertyName == Map.HasZoomEnabledProperty.PropertyName)
				UpdateHasZoomEnabled();
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing && !_disposed)
			{
				_disposed = true;

				MessagingCenter.Unsubscribe<Map, MapSpan>(this, "MapMoveToRegion");

				if (Element != null)
					((ObservableCollection<Pin>)Element.Pins).CollectionChanged -= OnCollectionChanged;
			}
			base.Dispose(disposing);
		}

		bool _disposed;
		bool _firstZoomLevelChangeFired;
		Ellipse _userPositionCircle;

		void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			switch (e.Action)
			{
				case NotifyCollectionChangedAction.Add:
					foreach (Pin pin in e.NewItems)
						LoadPin(pin);
					break;
				case NotifyCollectionChangedAction.Move:
					// no matter
					break;
				case NotifyCollectionChangedAction.Remove:
					foreach (Pin pin in e.OldItems)
						RemovePin(pin);
					break;
				case NotifyCollectionChangedAction.Replace:
					foreach (Pin pin in e.OldItems)
						RemovePin(pin);
					foreach (Pin pin in e.NewItems)
						LoadPin(pin);
					break;
				case NotifyCollectionChangedAction.Reset:
					ClearPins();
					break;
			}
		}

		void LoadPins()
		{
			foreach (var pin in Element.Pins)
				LoadPin(pin);
		}

		void ClearPins()
		{
			Control.Children.Clear();
#pragma warning disable 4014 // don't wanna block UI thread
			UpdateIsShowingUser();
#pragma warning restore
		}

		void RemovePin(Pin pinToRemove)
		{
			var pushPin = Control.Children.FirstOrDefault(c =>
			{
				var pin = (c as PushPin);
				return (pin != null && pin.DataContext.Equals(pinToRemove));
			});

			if (pushPin != null)
				Control.Children.Remove(pushPin);
		}

		void LoadPin(Pin pin)
		{
			Control.Children.Add(new PushPin(pin));
		}

		async Task UpdateIsShowingUser()
		{
			if (Element.IsShowingUser)
			{
				var myGeolocator = new Geolocator();
				if (myGeolocator.LocationStatus != PositionStatus.NotAvailable &&
				    myGeolocator.LocationStatus != PositionStatus.Disabled)
				{
					var userPosition = await myGeolocator.GetGeopositionAsync();
					if (userPosition?.Coordinate != null)
						LoadUserPosition(userPosition.Coordinate, true);
				}
			}
			else if (_userPositionCircle != null && Control.Children.Contains(_userPositionCircle))
				Control.Children.Remove(_userPositionCircle);
		}

		async Task MoveToRegion(MapSpan span, MapAnimationKind animation = MapAnimationKind.Bow)
		{
			var nw = new BasicGeoposition
			{
				Latitude = span.Center.Latitude + span.LatitudeDegrees / 2,
				Longitude = span.Center.Longitude - span.LongitudeDegrees / 2
			};
			var se = new BasicGeoposition
			{
				Latitude = span.Center.Latitude - span.LatitudeDegrees / 2,
				Longitude = span.Center.Longitude + span.LongitudeDegrees / 2
			};
			var boundingBox = new GeoboundingBox(nw, se);
			await Control.TrySetViewBoundsAsync(boundingBox, null, animation);
		}

		async Task UpdateVisibleRegion()
		{
			if (Control == null || Element == null)
				return;

			if (!_firstZoomLevelChangeFired)
			{
				await MoveToRegion(Element.LastMoveToRegion, MapAnimationKind.None);
				_firstZoomLevelChangeFired = true;
				return;
			}
			Geopoint nw, se = null;
			try
			{
				Control.GetLocationFromOffset(new Windows.Foundation.Point(0, 0), out nw);
				Control.GetLocationFromOffset(new Windows.Foundation.Point(Control.ActualWidth, Control.ActualHeight), out se);
			}
			catch (Exception)
			{
				return;
			}

			if (nw != null && se != null)
			{
				var boundingBox = new GeoboundingBox(nw.Position, se.Position);
				var center = new Position(boundingBox.Center.Latitude, boundingBox.Center.Longitude);
				var latitudeDelta = Math.Abs(center.Latitude - boundingBox.NorthwestCorner.Latitude);
				var longitudeDelta = Math.Abs(center.Longitude - boundingBox.NorthwestCorner.Longitude);
				Element.VisibleRegion = new MapSpan(center, latitudeDelta, longitudeDelta);
			}
		}

		void LoadUserPosition(Geocoordinate userCoordinate, bool center)
		{
			var userPosition = new BasicGeoposition
			{
				Latitude = userCoordinate.Point.Position.Latitude,
				Longitude = userCoordinate.Point.Position.Longitude
			};

			var point = new Geopoint(userPosition);

			if (_userPositionCircle == null)
			{
				_userPositionCircle = new Ellipse
				{
					Stroke = new SolidColorBrush(Colors.White),
					Fill = new SolidColorBrush(Colors.Blue),
					StrokeThickness = 2,
					Height = 20,
					Width = 20,
					Opacity = 50
				};
			}

			if (Control.Children.Contains(_userPositionCircle))
				Control.Children.Remove(_userPositionCircle);

			MapControl.SetLocation(_userPositionCircle, point);
			MapControl.SetNormalizedAnchorPoint(_userPositionCircle, new Windows.Foundation.Point(0.5, 0.5));

			Control.Children.Add(_userPositionCircle);

			if (center)
			{
				Control.Center = point;
				Control.ZoomLevel = 13;
			}
		}

		void UpdateMapType()
		{
			switch (Element.MapType)
			{
				case MapType.Street:
					Control.Style = MapStyle.Road;
					break;
				case MapType.Satellite:
					Control.Style = MapStyle.Aerial;
					break;
				case MapType.Hybrid:
					Control.Style = MapStyle.AerialWithRoads;
					break;
			}
		}

#if WINDOWS_UWP
		void UpdateHasZoomEnabled()
		{
			Control.ZoomInteractionMode = Element.HasZoomEnabled
				? MapInteractionMode.GestureAndControl
				: MapInteractionMode.ControlOnly;
		}

		void UpdateHasScrollEnabled()
		{
			Control.PanInteractionMode = Element.HasScrollEnabled ? MapPanInteractionMode.Auto : MapPanInteractionMode.Disabled;
		}
#else
		void UpdateHasZoomEnabled()
		{
		}

		void UpdateHasScrollEnabled()
		{
		}
#endif
	}
}