forked from criticalmaps/criticalmaps-android
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMapFragment.java
More file actions
515 lines (426 loc) · 19.6 KB
/
MapFragment.java
File metadata and controls
515 lines (426 loc) · 19.6 KB
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
package de.stephanlindauer.criticalmaps.fragments;
import android.animation.AnimatorInflater;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.fragment.app.Fragment;
import com.squareup.otto.Subscribe;
import org.osmdroid.tileprovider.modules.SqlTileWriter;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.gestures.RotationGestureOverlay;
import org.osmdroid.views.overlay.infowindow.InfoWindow;
import java.util.Timer;
import java.util.TimerTask;
import javax.inject.Inject;
import javax.inject.Provider;
import de.stephanlindauer.criticalmaps.App;
import de.stephanlindauer.criticalmaps.R;
import de.stephanlindauer.criticalmaps.databinding.FragmentMapBinding;
import de.stephanlindauer.criticalmaps.events.GpsStatusChangedEvent;
import de.stephanlindauer.criticalmaps.events.NetworkConnectivityChangedEvent;
import de.stephanlindauer.criticalmaps.events.NewLocationEvent;
import de.stephanlindauer.criticalmaps.events.NewServerResponseEvent;
import de.stephanlindauer.criticalmaps.handler.GetLocationHandler;
import de.stephanlindauer.criticalmaps.handler.ShowGpxHandler;
import de.stephanlindauer.criticalmaps.managers.LocationUpdateManager;
import de.stephanlindauer.criticalmaps.model.OtherUsersLocationModel;
import de.stephanlindauer.criticalmaps.model.OwnLocationModel;
import de.stephanlindauer.criticalmaps.overlays.LocationMarker;
import de.stephanlindauer.criticalmaps.prefs.SharedPrefsKeys;
import de.stephanlindauer.criticalmaps.provider.EventBus;
import de.stephanlindauer.criticalmaps.utils.AlertBuilder;
import de.stephanlindauer.criticalmaps.utils.MapViewUtils;
import info.metadude.android.typedpreferences.BooleanPreference;
public class MapFragment extends Fragment {
private final static String KEY_MAP_ZOOMLEVEL = "map_zoomlevel";
private final static String KEY_MAP_POSITION = "map_position";
private final static String KEY_MAP_ORIENTATION = "map_orientation";
private final static String KEY_INITIAL_LOCATION_SET = "initial_location_set";
private final static double DEFAULT_ZOOM_LEVEL = 12;
private final static double NO_GPS_PERMISSION_ZOOM_LEVEL = 3;
private final int SERVER_SYNC_INTERVAL = 30 * 1000; // 30 sec
@Inject
Provider<GetLocationHandler> getLocationHandler;
@Inject
OwnLocationModel ownLocationModel;
@Inject
OtherUsersLocationModel otherUsersLocationModel;
@Inject
EventBus eventBus;
@Inject
LocationUpdateManager locationUpdateManager;
@Inject
ShowGpxHandler showGpxHandler;
@Inject
SharedPreferences sharedPreferences;
private MapView mapView;
private InfoWindow observerInfoWindow;
private final GeoPoint defaultGeoPoint = new GeoPoint(52.499571, 13.4140875, 15);
private boolean isInitialLocationSet = false;
private ObjectAnimator gpsSearchingAnimator;
// cache drawables
private Drawable locationIcon;
private Drawable ownLocationIcon;
private Drawable ownLocationIconObserver;
private FragmentMapBinding binding;
private Timer timerGetLocation;
private final View.OnClickListener centerLocationOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ownLocationModel.ownLocation != null)
animateToLocation(ownLocationModel.ownLocation);
}
};
private final View.OnClickListener rotationNorthOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
float currentRotation = mapView.getMapOrientation() % 360;
if (currentRotation == 0.0f) {
// no animation required; also works around bug where map does a full rotation
// because of mapView wrapping 360° to 0° while View allows 360°
return;
}
if (currentRotation < 0.0f) {
currentRotation = 360.0f + currentRotation;
binding.mapSetNorthFab.setRotation(currentRotation);
mapView.setMapOrientation(currentRotation);
}
float destinationRotation = currentRotation > 180.0f ? 360.0f : 0.0f;
ViewCompat.animate(binding.mapSetNorthFab)
.rotation(destinationRotation)
.setDuration(300L)
.setUpdateListener(view -> mapView.setMapOrientation(view.getRotation()))
.start();
}
};
private final View.OnClickListener noGpsOnClickListener = v -> AlertBuilder.show(getActivity(),
R.string.map_no_gps_title,
R.string.map_no_gps_text);
private final View.OnClickListener gpsDisabledOnClickListener =
v -> AlertBuilder.show(getActivity(),
R.string.map_gps_disabled_title,
R.string.map_gps_disabled_text);
private final View.OnClickListener gpsNoPermissionsOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
locationUpdateManager.requestPermission();
}
};
private final View.OnClickListener gpsPermissionsPermanentlyDeniedOnClickListener = v ->
new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme)
.setTitle(R.string.map_gps_permissions_permanently_denied_title)
.setMessage(R.string.map_gps_permissions_permanently_denied_text)
.setNegativeButton(R.string.no, null)
.setPositiveButton(R.string.permissions_open_settings, (dialog, which) -> {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", getActivity().getPackageName(), null));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
})
.create()
.show();
private final View.OnClickListener searchingForLocationOnClickListener = v ->
Toast.makeText(getActivity(), R.string.map_searching_for_location, Toast.LENGTH_SHORT)
.show();
private final SharedPreferences.OnSharedPreferenceChangeListener observerModeOnSharedPreferenceChangeListener =
(sharedPreferences, key) -> {
if (SharedPrefsKeys.OBSERVER_MODE_ACTIVE.equals(key)) {
refreshView();
}
};
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
binding = FragmentMapBinding.inflate(inflater, container, false);
//noinspection ConstantConditions
locationIcon = AppCompatResources.getDrawable(getActivity(), R.drawable.ic_map_marker);
ownLocationIcon = AppCompatResources.getDrawable(
getActivity(), R.drawable.ic_map_marker_own);
ownLocationIconObserver = AppCompatResources.getDrawable(
getActivity(), R.drawable.ic_map_marker_observer);
return binding.getRoot();
}
@Override
public void onActivityCreated(final Bundle savedState) {
super.onActivityCreated(savedState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
adjustToWindowsInsets();
}
App.components().inject(this);
binding.mapOsmNoticeText.setMovementMethod(LinkMovementMethod.getInstance());
mapView = MapViewUtils.createMapView(getActivity());
binding.mapContainerLayout.addView(mapView);
observerInfoWindow = MapViewUtils.createObserverInfoWindow(mapView);
binding.mapSetCenterFab.setOnClickListener(centerLocationOnClickListener);
binding.mapSetNorthFab.setOnClickListener(rotationNorthOnClickListener);
binding.mapNoDataConnectivityFab.setOnClickListener(v -> AlertBuilder.show(getActivity(),
R.string.map_no_internet_connection_title,
R.string.map_no_internet_connection_text));
if (new BooleanPreference(sharedPreferences, SharedPrefsKeys.DISABLE_MAP_ROTATION).get()) {
binding.mapSetNorthFab.setVisibility(View.GONE);
} else {
RotationGestureOverlay rotationGestureOverlay = new RotationGestureOverlay(mapView) {
@Override
public void onRotate(float deltaAngle) {
super.onRotate(deltaAngle);
binding.mapSetNorthFab.setRotation(mapView.getMapOrientation());
}
};
rotationGestureOverlay.setEnabled(true);
mapView.setMultiTouchControls(true);
mapView.getOverlays().add(rotationGestureOverlay);
}
if (savedState != null) {
Double zoomLevel = (Double) savedState.get(KEY_MAP_ZOOMLEVEL);
GeoPoint position = savedState.getParcelable(KEY_MAP_POSITION);
Float orientation = (Float) savedState.get(KEY_MAP_ORIENTATION);
if (zoomLevel != null && position != null && orientation != null) {
mapView.getController().setZoom(zoomLevel);
if (!new BooleanPreference(sharedPreferences, SharedPrefsKeys.DISABLE_MAP_ROTATION)
.get()) {
mapView.setMapOrientation(orientation);
}
setToLocation(position);
}
isInitialLocationSet = savedState.getBoolean(KEY_INITIAL_LOCATION_SET, false);
}
binding.mapSetNorthFab.setRotation(mapView.getMapOrientation());
showGpxHandler.showGpx(mapView);
if (!LocationUpdateManager.checkPermission()) {
zoomToLocation(defaultGeoPoint, NO_GPS_PERMISSION_ZOOM_LEVEL);
}
}
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void adjustToWindowsInsets() {
// No-op on < API21
ViewCompat.setOnApplyWindowInsetsListener(binding.mapOverlayContainerLayout, (v, insets) -> {
// inset the map overlays for the status bar
v.setPaddingRelative(
v.getPaddingStart(), v.getPaddingTop() + insets.getSystemWindowInsetTop(),
v.getPaddingEnd(), v.getPaddingBottom());
// clear this listener so insets aren't re-applied
ViewCompat.setOnApplyWindowInsetsListener(binding.mapOverlayContainerLayout, null);
return insets;
});
// without this insets aren't reapplied on fragment changes
ViewCompat.requestApplyInsets(binding.mapOverlayContainerLayout);
}
private void refreshView() {
for (Overlay overlay : mapView.getOverlays()) {
if (overlay instanceof LocationMarker) {
mapView.getOverlays().remove(overlay);
}
}
for (GeoPoint currentOtherUsersLocation : otherUsersLocationModel.getOtherUsersLocations()) {
LocationMarker otherPeoplesMarker = new LocationMarker(mapView);
otherPeoplesMarker.setPosition(currentOtherUsersLocation);
otherPeoplesMarker.setIcon(locationIcon);
mapView.getOverlays().add(otherPeoplesMarker);
}
if (ownLocationModel.ownLocation != null) {
GeoPoint currentUserLocation = ownLocationModel.ownLocation;
LocationMarker ownMarker = new LocationMarker(mapView);
ownMarker.setPosition(currentUserLocation);
if (new BooleanPreference(
sharedPreferences, SharedPrefsKeys.OBSERVER_MODE_ACTIVE).get()) {
ownMarker.setIcon(ownLocationIconObserver);
ownMarker.setInfoWindow(observerInfoWindow);
// since we're currently creating new markers on every refresh, this workaround
// is needed to update the info window's position if it's open
if (observerInfoWindow.isOpen()) {
ownMarker.showInfoWindow();
}
} else {
observerInfoWindow.close();
ownMarker.setIcon(ownLocationIcon);
}
mapView.getOverlays().add(ownMarker);
}
mapView.invalidate();
}
@Override
public void onResume() {
super.onResume();
eventBus.register(this);
sharedPreferences.registerOnSharedPreferenceChangeListener(
observerModeOnSharedPreferenceChangeListener);
startGetLocationTimer();
}
private void handleFirstLocationUpdate() {
setGpsStatusFixed();
zoomToLocation(ownLocationModel.ownLocation, DEFAULT_ZOOM_LEVEL);
isInitialLocationSet = true;
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putDouble(KEY_MAP_ZOOMLEVEL, mapView.getZoomLevelDouble());
outState.putParcelable(KEY_MAP_POSITION, (GeoPoint) mapView.getMapCenter());
outState.putFloat(KEY_MAP_ORIENTATION, mapView.getMapOrientation());
outState.putBoolean(KEY_INITIAL_LOCATION_SET, isInitialLocationSet);
}
@Override
public void onPause() {
super.onPause();
stopGetLocationTimer();
eventBus.unregister(this);
sharedPreferences.unregisterOnSharedPreferenceChangeListener(
observerModeOnSharedPreferenceChangeListener);
}
@Override
public void onDestroyView() {
super.onDestroyView();
// properly closes the cache db since it's stored in a static field in osmdroid...
try {
((SqlTileWriter) mapView.getTileProvider().getTileWriter()).refreshDb();
} catch (Exception ignored) {
// nothing we can do
}
mapView = null;
binding = null;
}
@Subscribe
public void handleNewServerData(NewServerResponseEvent e) {
refreshView();
}
@Subscribe
public void handleNewLocation(NewLocationEvent e) {
// if this is the first location update handle it accordingly
if (ownLocationModel.ownLocation != null && !isInitialLocationSet) {
handleFirstLocationUpdate();
}
refreshView();
}
@Subscribe
public void handleNetworkConnectivityChanged(NetworkConnectivityChangedEvent e) {
if (e.isConnected) {
binding.mapNoDataConnectivityFab.hide();
} else {
binding.mapNoDataConnectivityFab.show();
}
if (e.isConnected && timerGetLocation == null) {
startGetLocationTimer();
} else {
stopGetLocationTimer();
}
}
@Subscribe
public void handleGpsStatusChangedEvent(GpsStatusChangedEvent e) {
if (e.status == GpsStatusChangedEvent.Status.NONEXISTENT) {
setGpsStatusNonexistent();
} else if (e.status == GpsStatusChangedEvent.Status.DISABLED) {
setGpsStatusDisabled();
} else if (e.status == GpsStatusChangedEvent.Status.PERMISSION_PERMANENTLY_DENIED) {
setGpsStatusPermissionsPermanentlyDenied();
} else if (e.status == GpsStatusChangedEvent.Status.NO_PERMISSIONS) {
setGpsStatusNoPermissions();
} else if (e.status == GpsStatusChangedEvent.Status.LOW_ACCURACY ||
e.status == GpsStatusChangedEvent.Status.HIGH_ACCURACY) {
if (ownLocationModel.ownLocation != null) {
setGpsStatusFixed();
} else {
setGpsStatusSearching();
}
}
}
private void setGpsStatusNonexistent() {
cancelGpsSearchingAnimationIfRunning();
setGpsStatusCommon(R.color.map_fab_warning, R.drawable.ic_map_no_gps,
noGpsOnClickListener);
}
private void setGpsStatusDisabled() {
cancelGpsSearchingAnimationIfRunning();
setGpsStatusCommon(R.color.map_fab_warning, R.drawable.ic_map_no_gps,
gpsDisabledOnClickListener);
}
private void setGpsStatusNoPermissions() {
cancelGpsSearchingAnimationIfRunning();
setGpsStatusCommon(R.color.map_fab_warning, R.drawable.ic_map_no_gps,
gpsNoPermissionsOnClickListener);
}
private void setGpsStatusPermissionsPermanentlyDenied() {
cancelGpsSearchingAnimationIfRunning();
setGpsStatusCommon(R.color.map_fab_warning, R.drawable.ic_map_no_gps,
gpsPermissionsPermanentlyDeniedOnClickListener);
}
private void setGpsStatusFixed() {
cancelGpsSearchingAnimationIfRunning();
setGpsStatusCommon(R.color.colorSecondary, R.drawable.ic_map_center_location,
centerLocationOnClickListener);
}
private void setGpsStatusSearching() {
cancelGpsSearchingAnimationIfRunning();
setGpsStatusCommon(R.color.map_fab_searching, R.drawable.ic_map_gps_not_fixed,
searchingForLocationOnClickListener);
gpsSearchingAnimator = (ObjectAnimator) AnimatorInflater.loadAnimator(
getActivity(),
R.animator.map_gps_fab_searching_animation);
gpsSearchingAnimator.setTarget(binding.mapSetCenterFab);
gpsSearchingAnimator.start();
}
private void setGpsStatusCommon(@ColorRes int colorResId, @DrawableRes int iconResId,
View.OnClickListener onClickListener) {
//noinspection ConstantConditions
binding.mapSetCenterFab.setBackgroundTintList(
ContextCompat.getColorStateList(getActivity(), colorResId));
binding.mapSetCenterFab.setImageResource(iconResId);
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
binding.mapSetCenterFab.refreshDrawableState();
}
binding.mapSetCenterFab.setOnClickListener(onClickListener);
}
private void cancelGpsSearchingAnimationIfRunning() {
if (gpsSearchingAnimator != null) {
gpsSearchingAnimator.cancel();
binding.mapSetCenterFab.setAlpha(1.0f);
}
}
private void zoomToLocation(final GeoPoint location, final double zoomLevel) {
// TODO use setCenter() + zoomTo() here; currently broken and ends up in a wrong location
mapView.getController().setZoom(zoomLevel);
animateToLocation(location);
}
private void animateToLocation(final GeoPoint location) {
mapView.getController().animateTo(location);
}
private void setToLocation(final GeoPoint location) {
mapView.getController().setCenter(location);
}
private void startGetLocationTimer() {
stopGetLocationTimer();
timerGetLocation = new Timer();
TimerTask timerTaskPullServer = new TimerTask() {
@Override
public void run() {
getLocationHandler.get().execute();
}
};
timerGetLocation.schedule(timerTaskPullServer, 0, SERVER_SYNC_INTERVAL);
}
private void stopGetLocationTimer() {
if (timerGetLocation != null) {
timerGetLocation.cancel();
timerGetLocation = null;
}
}
}