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
545 lines (447 loc) · 20.3 KB
/
MapFragment.java
File metadata and controls
545 lines (447 loc) · 20.3 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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
package de.stephanlindauer.criticalmaps.fragments;
import static de.stephanlindauer.criticalmaps.events.Events.NEW_LOCATION_EVENT;
import static de.stephanlindauer.criticalmaps.utils.MapViewUtils.dpToInt;
import android.animation.AnimatorInflater;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Outline;
import android.net.Uri;
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.view.ViewOutlineProvider;
import android.widget.Toast;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import com.google.gson.JsonObject;
import com.squareup.otto.Subscribe;
import org.maplibre.android.camera.CameraPosition;
import org.maplibre.android.camera.CameraUpdateFactory;
import org.maplibre.android.geometry.LatLng;
import org.maplibre.android.maps.MapLibreMap;
import org.maplibre.android.maps.MapView;
import org.maplibre.android.maps.Style;
import org.maplibre.android.style.sources.GeoJsonSource;
import org.maplibre.geojson.Feature;
import org.maplibre.geojson.FeatureCollection;
import org.maplibre.geojson.Point;
import java.util.ArrayList;
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.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_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 MapLibreMap map;
private Style mapStyle;
// private InfoWindow observerInfoWindow;
private final LatLng defaultGeoPoint = new LatLng(52.499571, 13.4140875);
private boolean isInitialLocationSet = false;
private ObjectAnimator gpsSearchingAnimator;
private FragmentMapBinding binding;
private Timer timerGetLocation;
private final View.OnClickListener centerLocationOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ownLocationModel.ownLocation != null) {
CameraPosition cameraPosition =
new CameraPosition.Builder().target(ownLocationModel.ownLocation).build();
animateToCameraPosition(cameraPosition);
}
}
};
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);
return binding.getRoot();
}
@Override
public void onActivityCreated(final Bundle savedState) {
super.onActivityCreated(savedState);
adjustToWindowsInsets();
App.components().inject(this);
binding.mapOsmNoticeText.setMovementMethod(LinkMovementMethod.getInstance());
mapView = MapViewUtils.createMapView(getActivity());
binding.mapContainerLayout.addView(mapView);
mapView.getMapAsync(map -> {
this.map = map;
// Set shadow on compass
// NOTE: Needs to be before updating uiSettings below, otherwise compassView will be null!
View compassView = mapView.findViewWithTag("compassView");
compassView.setOutlineProvider(new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
outline.setOval(0, 0, view.getWidth(), view.getHeight());
}
});
compassView.setElevation(dpToInt(6));
// Set compass y position to align it with other fabs
View setCenterFab = binding.getRoot().findViewById(R.id.map_set_center_fab);
float setCenterFabY = setCenterFab.getY();
map.getUiSettings().setCompassMargins(
dpToInt(18) + binding.mapOverlayContainerLayout.getPaddingLeft(), // when started
Math.round(setCenterFabY + dpToInt(18)),
0,
0);
// TODO: save sprites and glyphs as local asset,
// see https://github.com/maplibre/flutter-maplibre-gl/issues/338
Style.Builder styleBuilder = new Style.Builder().fromUri("asset://styles/versatilescolorful.json");
map.setStyle(styleBuilder, style -> {
mapStyle = style;
MapViewUtils.setupSourcesAndLayers(getActivity(), mapStyle);
showGpxHandler.showGpx(mapStyle);
// trigger fake location update in case fix was acquired already during map init
handleNewLocation(NEW_LOCATION_EVENT);
});
});
mapView.onCreate(savedState); // TODO: Should be onViewCreated
// observerInfoWindow = MapViewUtils.createObserverInfoWindow(mapView);
binding.mapSetCenterFab.setOnClickListener(centerLocationOnClickListener);
binding.mapNoDataConnectivityFab.setOnClickListener(v -> AlertBuilder.show(getActivity(),
R.string.map_no_internet_connection_title,
R.string.map_no_internet_connection_text));
if (savedState != null) {
isInitialLocationSet = savedState.getBoolean(KEY_INITIAL_LOCATION_SET, false);
}
if (!LocationUpdateManager.checkPermission()) {
zoomToLocation(defaultGeoPoint, NO_GPS_PERMISSION_ZOOM_LEVEL);
}
}
private void adjustToWindowsInsets() {
// inset the map overlays for the status bar
final int originalContainerPaddingTop = binding.mapOverlayContainerLayout.getPaddingTop();
final int originalContainerPaddingLeft = binding.mapOverlayContainerLayout.getPaddingLeft();
final int originalContainerPaddingRight = binding.mapOverlayContainerLayout.getPaddingRight();
ViewCompat.setOnApplyWindowInsetsListener(binding.mapOverlayContainerLayout, (v, insets) -> {
Insets systemBarsInsets = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(
originalContainerPaddingLeft + systemBarsInsets.left,
originalContainerPaddingTop + systemBarsInsets.top,
originalContainerPaddingRight + systemBarsInsets.right,
v.getPaddingBottom());
if (map != null) {
map.getUiSettings().setCompassMargins(
dpToInt(18) + binding.mapOverlayContainerLayout.getPaddingLeft(), // when started
map.getUiSettings().getCompassMarginTop(),
0,
0);
}
return insets;
});
// inset attribution
ViewGroup.MarginLayoutParams lpNoticeText =
(ViewGroup.MarginLayoutParams) binding.mapOsmNoticeText.getLayoutParams();
final int originalNoticeTextBottomMargin = lpNoticeText.bottomMargin;
ViewCompat.setOnApplyWindowInsetsListener(binding.mapOsmNoticeText, (v, insets) -> {
Insets systemBarsInsets = insets.getInsets(WindowInsetsCompat.Type.systemBars());
lpNoticeText.bottomMargin = originalNoticeTextBottomMargin + systemBarsInsets.bottom;
v.setLayoutParams(lpNoticeText);
return WindowInsetsCompat.CONSUMED;
});
}
private FeatureCollection getOtherUsersFeatureCollection() {
ArrayList<Feature> features = new ArrayList<>();
otherUsersLocationModel.getOtherUsersLocations().forEach((deviceId, location) -> {
JsonObject properties = new JsonObject();
properties.addProperty("deviceId", deviceId);
features.add(Feature.fromGeometry(Point.fromLngLat(location.getLongitude(), location.getLatitude()), properties));
});
return FeatureCollection.fromFeatures(features);
}
private FeatureCollection getOwnUserFeatureCollection() {
ArrayList<Feature> features = new ArrayList<>();
LatLng location = ownLocationModel.ownLocation;
JsonObject properties = new JsonObject();
properties.addProperty("deviceId", "own");
features.add(Feature.fromGeometry(Point.fromLngLat(location.getLongitude(), location.getLatitude()), properties));
return FeatureCollection.fromFeatures(features);
}
private void refreshView() {
if (map == null || mapStyle == null) {
return;
}
FeatureCollection otherUsersFeatures = getOtherUsersFeatureCollection();
GeoJsonSource otherUsersLocationsSource =
(GeoJsonSource) mapStyle.getSource("otherUsersLocationsSource");
otherUsersLocationsSource.setGeoJson(otherUsersFeatures);
if (ownLocationModel.ownLocation != null) {
FeatureCollection ownUserFeatures = getOwnUserFeatureCollection();
FeatureCollection emptyFeatures =
FeatureCollection.fromJson("{\"type\":\"FeatureCollection\",\"features\":[]}");
GeoJsonSource ownUserLocationSourceObserver =
(GeoJsonSource) mapStyle.getSource("ownUserLocationSourceObserver");
GeoJsonSource ownUserLocationSource =
(GeoJsonSource) mapStyle.getSource("ownUserLocationSource");
if (new BooleanPreference(sharedPreferences, SharedPrefsKeys.OBSERVER_MODE_ACTIVE).get()) {
ownUserLocationSource.setGeoJson(emptyFeatures);
ownUserLocationSourceObserver.setGeoJson(ownUserFeatures);
} else {
ownUserLocationSource.setGeoJson(ownUserFeatures);
ownUserLocationSourceObserver.setGeoJson(emptyFeatures);
}
}
}
@Override
public void onStart() {
super.onStart();
mapView.onStart();
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
eventBus.register(this);
sharedPreferences.registerOnSharedPreferenceChangeListener(
observerModeOnSharedPreferenceChangeListener);
startGetLocationTimer();
}
private void handleFirstLocationUpdate() {
if (map == null) {
return;
}
setGpsStatusFixed();
zoomToLocation(ownLocationModel.ownLocation, DEFAULT_ZOOM_LEVEL);
isInitialLocationSet = true;
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
if (mapView != null && !mapView.isDestroyed()) {
mapView.onSaveInstanceState(outState);
}
outState.putBoolean(KEY_INITIAL_LOCATION_SET, isInitialLocationSet);
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
stopGetLocationTimer();
eventBus.unregister(this);
sharedPreferences.unregisterOnSharedPreferenceChangeListener(
observerModeOnSharedPreferenceChangeListener);
}
@Override
public void onStop() {
super.onStop();
mapView.onStop();
}
@Override
public void onLowMemory() {
super.onLowMemory();
if (mapView != null && !mapView.isDestroyed()) {
mapView.onLowMemory();
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
mapView.onDestroy();
mapView = null;
map = 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);
binding.mapSetCenterFab.setOnClickListener(onClickListener);
}
private void cancelGpsSearchingAnimationIfRunning() {
if (gpsSearchingAnimator != null) {
gpsSearchingAnimator.cancel();
binding.mapSetCenterFab.setAlpha(1.0f);
}
}
private void zoomToLocation(final LatLng location, final double zoomLevel) {
CameraPosition cameraPosition =
new CameraPosition.Builder().target(location).zoom(zoomLevel).build();
animateToCameraPosition(cameraPosition);
}
private void animateToCameraPosition(final CameraPosition cameraPosition) {
if (map == null) {
return;
}
map.animateCamera(
CameraUpdateFactory.newCameraPosition(cameraPosition), 2000, null);
}
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;
}
}
}