summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Maps.Android/MapRenderer.cs
blob: 0b426d3eed8f8990dae3e765e5fb6c1040128545 (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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using Android.OS;
using Java.Lang;
using Xamarin.Forms.Internals;
using Xamarin.Forms.Platform.Android;
using Math = System.Math;

namespace Xamarin.Forms.Maps.Android
{
	public class MapRenderer : ViewRenderer<Map, MapView>,
		GoogleMap.IOnCameraChangeListener, IOnMapReadyCallback
	{
		const string MoveMessageName = "MapMoveToRegion";

		static Bundle s_bundle;

		bool _disposed;

		bool _init = true;

		List<Marker> _markers;

		public MapRenderer()
		{
			AutoPackage = false;
		}

		protected Map Map => Element;

		protected GoogleMap NativeMap;

		internal static Bundle Bundle
		{
			set { s_bundle = value; }
		}

		public void OnCameraChange(CameraPosition pos)
		{
			UpdateVisibleRegion(pos.Target);
		}

		public override SizeRequest GetDesiredSize(int widthConstraint, int heightConstraint)
		{
			return new SizeRequest(new Size(Context.ToPixels(40), Context.ToPixels(40)));
		}

		protected override MapView CreateNativeControl()
		{
			return new MapView(Context);
		}

		protected override void Dispose(bool disposing)
		{
			if (_disposed)
			{
				return;
			}

			_disposed = true;

			if (disposing)
			{
				if (Element != null)
				{
					MessagingCenter.Unsubscribe<Map, MapSpan>(this, MoveMessageName);
					((ObservableCollection<Pin>)Element.Pins).CollectionChanged -= OnCollectionChanged;
				}

				if (NativeMap != null)
 				{
 					NativeMap.MyLocationEnabled = false;
 					NativeMap.SetOnCameraChangeListener(null);
 					NativeMap.InfoWindowClick -= MapOnMarkerClick;
 					NativeMap.Dispose();
					NativeMap = null;
				 }

				Control?.OnDestroy();
			}

			base.Dispose(disposing);
		}

		protected override void OnElementChanged(ElementChangedEventArgs<Map> e)
		{
			base.OnElementChanged(e);

			MapView oldMapView = Control;

			MapView mapView = CreateNativeControl();
			mapView.OnCreate(s_bundle);
			mapView.OnResume();
			SetNativeControl(mapView);

			if (e.OldElement != null)
			{
				Map oldMapModel = e.OldElement;
				((ObservableCollection<Pin>)oldMapModel.Pins).CollectionChanged -= OnCollectionChanged;

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

				if (NativeMap != null)
				{
					NativeMap.SetOnCameraChangeListener(null);
					NativeMap.InfoWindowClick -= MapOnMarkerClick;
					NativeMap = null;
				}

				oldMapView.Dispose();
			}

			Control.GetMapAsync(this);

			MessagingCenter.Subscribe<Map, MapSpan>(this, MoveMessageName, OnMoveToRegionMessage, Map);

			var incc = Map.Pins as INotifyCollectionChanged;
			if (incc != null)
			{
				incc.CollectionChanged += OnCollectionChanged;
			}
		}

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

			if (e.PropertyName == Map.MapTypeProperty.PropertyName)
			{
				SetMapType();
				return;
			}

			GoogleMap gmap = NativeMap;
			if (gmap == null)
			{
				return;
			}

			if (e.PropertyName == Map.IsShowingUserProperty.PropertyName)
			{
				gmap.MyLocationEnabled = gmap.UiSettings.MyLocationButtonEnabled = Map.IsShowingUser;
			}
			else if (e.PropertyName == Map.HasScrollEnabledProperty.PropertyName)
			{
				gmap.UiSettings.ScrollGesturesEnabled = Map.HasScrollEnabled;
			}
			else if (e.PropertyName == Map.HasZoomEnabledProperty.PropertyName)
			{
				gmap.UiSettings.ZoomControlsEnabled = Map.HasZoomEnabled;
				gmap.UiSettings.ZoomGesturesEnabled = Map.HasZoomEnabled;
			}
		}

		protected override void OnLayout(bool changed, int l, int t, int r, int b)
		{
			base.OnLayout(changed, l, t, r, b);

			if (_init)
			{
				if (NativeMap != null)
				{
					MoveToRegion(Element.LastMoveToRegion, false);
					OnCollectionChanged(Element.Pins, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
					_init = false;
				}
			}
			else if (changed)
			{
				if (NativeMap != null)
				{
					UpdateVisibleRegion(NativeMap.CameraPosition.Target);
				}
				MoveToRegion(Element.LastMoveToRegion, false);
			}
		}
		
		protected virtual void OnMapReady(GoogleMap map)
		{
			if (map == null)
			{
				return;
			}
			
			map.SetOnCameraChangeListener(this);
			map.InfoWindowClick += MapOnMarkerClick;
			
			map.UiSettings.ZoomControlsEnabled = Map.HasZoomEnabled;
			map.UiSettings.ZoomGesturesEnabled = Map.HasZoomEnabled;
			map.UiSettings.ScrollGesturesEnabled = Map.HasScrollEnabled;
			map.MyLocationEnabled = map.UiSettings.MyLocationButtonEnabled = Map.IsShowingUser;
			SetMapType();
		}
		
		protected virtual MarkerOptions CreateMarker(Pin pin)
		{
			var opts = new MarkerOptions();
			opts.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
			opts.SetTitle(pin.Label);
			opts.SetSnippet(pin.Address);
			
			return opts;
		}

		void AddPins(IList pins)
		{
			GoogleMap map = NativeMap;
			if (map == null)
			{
				return;
			}

			if (_markers == null)
			{
				_markers = new List<Marker>();
			}

			_markers.AddRange(pins.Cast<Pin>().Select(p =>
			{
				Pin pin = p;
				var opts = CreateMarker(pin);
				var marker = map.AddMarker(opts);

				// associate pin with marker for later lookup in event handlers
				pin.Id = marker.Id;
				return marker;
			}));
		}

		void MapOnMarkerClick(object sender, GoogleMap.InfoWindowClickEventArgs eventArgs)
		{
			// clicked marker
			var marker = eventArgs.Marker;

			// lookup pin
			Pin targetPin = null;
			for (var i = 0; i < Map.Pins.Count; i++)
			{
				Pin pin = Map.Pins[i];
				if ((string)pin.Id != marker.Id)
				{
					continue;
				}

				targetPin = pin;
				break;
			}

			// only consider event handled if a handler is present. 
			// Else allow default behavior of displaying an info window.
			targetPin?.SendTap();
		}

		void MoveToRegion(MapSpan span, bool animate)
		{
			GoogleMap map = NativeMap;
			if (map == null)
			{
				return;
			}

			span = span.ClampLatitude(85, -85);
			var ne = new LatLng(span.Center.Latitude + span.LatitudeDegrees / 2,
				span.Center.Longitude + span.LongitudeDegrees / 2);
			var sw = new LatLng(span.Center.Latitude - span.LatitudeDegrees / 2,
				span.Center.Longitude - span.LongitudeDegrees / 2);
			CameraUpdate update = CameraUpdateFactory.NewLatLngBounds(new LatLngBounds(sw, ne), 0);

			try
			{
				if (animate)
				{
					map.AnimateCamera(update);
				}
				else
				{
					map.MoveCamera(update);
				}
			}
			catch (IllegalStateException exc)
			{
				System.Diagnostics.Debug.WriteLine("MoveToRegion exception: " + exc);
				Log.Warning("Xamarin.Forms MapRenderer", $"MoveToRegion exception: {exc}");
			}
		}

		void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
		{
			switch (notifyCollectionChangedEventArgs.Action)
			{
				case NotifyCollectionChangedAction.Add:
					AddPins(notifyCollectionChangedEventArgs.NewItems);
					break;
				case NotifyCollectionChangedAction.Remove:
					RemovePins(notifyCollectionChangedEventArgs.OldItems);
					break;
				case NotifyCollectionChangedAction.Replace:
					RemovePins(notifyCollectionChangedEventArgs.OldItems);
					AddPins(notifyCollectionChangedEventArgs.NewItems);
					break;
				case NotifyCollectionChangedAction.Reset:
					_markers?.ForEach(m => m.Remove());
					_markers = null;
					AddPins((IList)Element.Pins);
					break;
				case NotifyCollectionChangedAction.Move:
					//do nothing
					break;
			}
		}

		void OnMoveToRegionMessage(Map s, MapSpan a)
		{
			MoveToRegion(a, true);
		}

		void RemovePins(IList pins)
		{
			GoogleMap map = NativeMap;
			if (map == null)
			{
				return;
			}
			if (_markers == null)
			{
				return;
			}

			foreach (Pin p in pins)
			{
				var marker = _markers.FirstOrDefault(m => (object)m.Id == p.Id);
				if (marker == null)
				{
					continue;
				}
				marker.Remove();
				_markers.Remove(marker);
			}
		}

		void SetMapType()
		{
			GoogleMap map = NativeMap;
			if (map == null)
			{
				return;
			}

			switch (Map.MapType)
			{
				case MapType.Street:
					map.MapType = GoogleMap.MapTypeNormal;
					break;
				case MapType.Satellite:
					map.MapType = GoogleMap.MapTypeSatellite;
					break;
				case MapType.Hybrid:
					map.MapType = GoogleMap.MapTypeHybrid;
					break;
				default:
					throw new ArgumentOutOfRangeException();
			}
		}

		void UpdateVisibleRegion(LatLng pos)
		{
			GoogleMap map = NativeMap;
			if (map == null)
			{
				return;
			}
			Projection projection = map.Projection;
			int width = Control.Width;
			int height = Control.Height;
			LatLng ul = projection.FromScreenLocation(new global::Android.Graphics.Point(0, 0));
			LatLng ur = projection.FromScreenLocation(new global::Android.Graphics.Point(width, 0));
			LatLng ll = projection.FromScreenLocation(new global::Android.Graphics.Point(0, height));
			LatLng lr = projection.FromScreenLocation(new global::Android.Graphics.Point(width, height));
			double dlat = Math.Max(Math.Abs(ul.Latitude - lr.Latitude), Math.Abs(ur.Latitude - ll.Latitude));
			double dlong = Math.Max(Math.Abs(ul.Longitude - lr.Longitude), Math.Abs(ur.Longitude - ll.Longitude));
			Element.VisibleRegion = new MapSpan(new Position(pos.Latitude, pos.Longitude), dlat, dlong);
		}

		void IOnMapReadyCallback.OnMapReady(GoogleMap map)
		{
			NativeMap = map;
			OnMapReady(map);
		}
	}
}