-
-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathDisplayTrackMap.java
More file actions
576 lines (486 loc) · 18.2 KB
/
DisplayTrackMap.java
File metadata and controls
576 lines (486 loc) · 18.2 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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
package net.osmtracker.activity;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import androidx.preference.PreferenceManager;
import net.osmtracker.OSMTracker;
import net.osmtracker.R;
import net.osmtracker.db.TrackContentProvider;
import net.osmtracker.db.DataHelper;
import net.osmtracker.overlay.WayPointsOverlay;
import net.osmtracker.overlay.Polylines;
import org.osmdroid.api.IMapController;
import org.osmdroid.config.Configuration;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.tileprovider.tilesource.ITileSource;
import org.osmdroid.tileprovider.tilesource.XYTileSource;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.CustomZoomButtonsController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ScaleBarOverlay;
import org.osmdroid.views.overlay.mylocation.SimpleLocationOverlay;
import java.util.ArrayList;
import java.util.List;
/**
* Display current track over an OSM map.
* Based on <a href="http://osmdroid.googlecode.com/">osmdroid code</a>
*<P>
* Used only if {@link OSMTracker.Preferences#KEY_UI_DISPLAYTRACK_OSM} is set.
* Otherwise {@link DisplayTrack} is used (track only, no OSM background tiles).
*
* @author Viesturs Zarins
*
*/
public class DisplayTrackMap extends Activity {
private static final String TAG = DisplayTrackMap.class.getSimpleName();
/**
* Key for keeping the zoom level in the saved instance bundle
*/
private static final String CURRENT_ZOOM = "currentZoom";
/**
* Key for keeping scrolled left position of OSM view activity re-creation
*/
private static final String CURRENT_SCROLL_X = "currentScrollX";
/**
* Key for keeping scrolled top position of OSM view across activity re-creation
*/
private static final String CURRENT_SCROLL_Y = "currentScrollY";
/**
* Key for keeping whether the map display should be centered to the gps location
*/
private static final String CURRENT_CENTER_TO_GPS_POS = "currentCenterToGpsPos";
/**
* Key for keeping whether the map display was zoomed and centered
* on an old track id loaded from the database (boolean {@link #zoomedToTrackAlready})
*/
private static final String CURRENT_ZOOMED_TO_TRACK = "currentZoomedToTrack";
/**
* Key for keeping the last zoom level across app. restart
*/
private static final String LAST_ZOOM = "lastZoomLevel";
/**
* Default zoom level
*/
private static final int DEFAULT_ZOOM = 16;
/**
* Default zoom level for center with zoom
*/
private static final double CENTER_DEFAULT_ZOOM_LEVEL = 18;
/**
* Animation duration in milliseconds for center with zoom
*/
private static final long ANIMATION_DURATION_MS = 1000;
/**
* Request Code for picking overlaid track
*/
public final static int RC_PICK_OVERLAID = 1;
/**
* Main OSM view
*/
private MapView osmView;
/**
* Controller to interact with view
*/
private IMapController osmViewController;
/**
* OSM view overlay that displays current location
*/
private SimpleLocationOverlay myLocationOverlay;
/**
* OSM view overlay that displays current path
*/
private Polylines polylines;
/**
* OSM view overlay that displays path of other track for comparison
*/
private Polylines polylinesOverlaid;
/**
* OSM view overlay that displays waypoints
*/
private WayPointsOverlay wayPointsOverlay;
/**
* OSM view overlay for the map scale bar
*/
private ScaleBarOverlay scaleBarOverlay;
/**
* Current track id
*/
private long currentTrackId;
/**
* Current overlaid track id
*/
private long overlaidTrackId=0;
/**
* whether the map display should be centered to the gps location
*/
private boolean centerToGpsPos = true;
/**
* whether the map display was already zoomed and centered
* on an old track loaded from the database (should be done only once).
*/
private boolean zoomedToTrackAlready = false;
/**
* the last position we know
*/
private GeoPoint currentPosition;
/**
* The row id of the last location read from the database that has been added to the
* list of layout points. Using this we to reduce DB load by only reading new points.
* Initially null, to indicate that no data has yet been read.
*/
private Integer lastTrackPointIdProcessed = null;
/**
* The id of the last segment
*/
private int prevSegmentId=-1;
/**
* Observes changes on track points
*/
private ContentObserver trackpointContentObserver;
/**
* Keeps the SharedPreferences
*/
private SharedPreferences prefs = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// loading the preferences
prefs = PreferenceManager.getDefaultSharedPreferences(this);
setContentView(R.layout.displaytrackmap);
currentTrackId = getIntent().getExtras().getLong(TrackContentProvider.Schema.COL_TRACK_ID);
setTitle(getTitle() + ": #" + currentTrackId);
final DataHelper dataHelper = new DataHelper(this);
overlaidTrackId = dataHelper.queryOverlay(currentTrackId,
getContentResolver());
// Initialize OSM view
Configuration.getInstance().load(this, prefs);
osmView = findViewById(R.id.displaytrackmap_osmView);
// pinch to zoom
osmView.setMultiTouchControls(true);
osmView.getZoomController().setVisibility(CustomZoomButtonsController.Visibility.NEVER);
// we'll use osmView to define if the screen is always on or not
osmView.setKeepScreenOn(prefs.getBoolean(OSMTracker.Preferences.KEY_UI_DISPLAY_KEEP_ON, OSMTracker.Preferences.VAL_UI_DISPLAY_KEEP_ON));
osmViewController = osmView.getController();
// Check if there is a saved zoom level
if (savedInstanceState != null) {
osmViewController.setZoom(savedInstanceState.getInt(CURRENT_ZOOM, DEFAULT_ZOOM));
osmView.scrollTo(savedInstanceState.getInt(CURRENT_SCROLL_X, 0),
savedInstanceState.getInt(CURRENT_SCROLL_Y, 0));
centerToGpsPos = savedInstanceState.getBoolean(CURRENT_CENTER_TO_GPS_POS, centerToGpsPos);
zoomedToTrackAlready = savedInstanceState.getBoolean(CURRENT_ZOOMED_TO_TRACK, zoomedToTrackAlready);
} else {
// Try to get last zoom Level from Shared Preferences
SharedPreferences settings = getPreferences(MODE_PRIVATE);
osmViewController.setZoom(settings.getInt(LAST_ZOOM, DEFAULT_ZOOM));
}
selectTileSource();
setTileDpiScaling();
createOverlays();
// Create content observer for track points
trackpointContentObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange) {
pathChanged(polylines, currentTrackId);
}
};
// Register listeners for zoom buttons
findViewById(R.id.displaytrackmap_imgZoomIn).setOnClickListener(v -> osmViewController.zoomIn());
findViewById(R.id.displaytrackmap_imgZoomOut).setOnClickListener(v -> osmViewController.zoomOut());
findViewById(R.id.displaytrackmap_imgZoomCenter).setOnClickListener(view -> {
centerToGpsPos = true;
if (currentPosition != null) {
osmViewController.animateTo(currentPosition,CENTER_DEFAULT_ZOOM_LEVEL, ANIMATION_DURATION_MS);
}
});
}
/**
* Sets the map tile provider according to the user's demands in the settings.
*/
public void selectTileSource() {
String mapTile = prefs.getString(OSMTracker.Preferences.KEY_UI_MAP_TILE, OSMTracker.Preferences.VAL_UI_MAP_TILE_MAPNIK);
Log.e("TileMapName active", mapTile);
osmView.setTileSource(selectMapTile(mapTile));
}
/**
* Make text on map better readable on high DPI displays
*/
public void setTileDpiScaling() {
osmView.setTilesScaledToDpi(true);
}
static {
TileSourceFactory.addTileSource(new XYTileSource("CyclOSM",
0, 18, 256, ".png",
new String[] {
"https://a.tile-cyclosm.openstreetmap.fr/cyclosm/",
"https://b.tile-cyclosm.openstreetmap.fr/cyclosm/",
"https://c.tile-cyclosm.openstreetmap.fr/cyclosm/"},
"© OpenStreetMap contributors"));
}
/**
* Returns a ITileSource for the map according to the selected mapTile
* String. The default is mapnik.
*
* @param mapTile String that is the name of the tile provider
* @return ITileSource with the selected Tile-Source
*/
private ITileSource selectMapTile(String mapTile) {
try {
return TileSourceFactory.getTileSource(mapTile);
} catch (Exception e) {
Log.e(TAG, "Invalid tile source '"+mapTile+"'", e);
Log.e(TAG, "Default tile source selected: '" + TileSourceFactory.DEFAULT_TILE_SOURCE.name() +"'");
return TileSourceFactory.DEFAULT_TILE_SOURCE;
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(CURRENT_ZOOM, osmView.getZoomLevel());
outState.putInt(CURRENT_SCROLL_X, osmView.getScrollX());
outState.putInt(CURRENT_SCROLL_Y, osmView.getScrollY());
outState.putBoolean(CURRENT_CENTER_TO_GPS_POS, centerToGpsPos);
outState.putBoolean(CURRENT_ZOOMED_TO_TRACK, zoomedToTrackAlready);
super.onSaveInstanceState(outState);
}
@Override
protected void onResume() {
super.onResume();
resumeActivity();
}
private void resumeActivity() {
// setKeepScreenOn depending on user's preferences
osmView.setKeepScreenOn(prefs.getBoolean(OSMTracker.Preferences.KEY_UI_DISPLAY_KEEP_ON, OSMTracker.Preferences.VAL_UI_DISPLAY_KEEP_ON));
// display "other" track
if(overlaidTrackId != 0) {
// from the database to populate the path layout
lastTrackPointIdProcessed = null;
prevSegmentId = -1;
// Reload path
pathChanged(polylinesOverlaid, overlaidTrackId);
}
// Forget the last waypoint read from the DB
// This ensures that all waypoints for the track will be reloaded
// from the database to populate the path layout
lastTrackPointIdProcessed = null;
prevSegmentId = -1;
// Register content observer for any track point changes
getContentResolver().registerContentObserver(
TrackContentProvider.trackPointsUri(currentTrackId),
true, trackpointContentObserver);
// Reload path a first time after resume. If
// trackpointObserver was already invoked just now, this becomes
// a no-op
pathChanged(polylines, currentTrackId);
selectTileSource();
setTileDpiScaling();
// Refresh way points
wayPointsOverlay.refresh();
}
@Override
protected void onPause() {
// Unregister content observer
getContentResolver().unregisterContentObserver(trackpointContentObserver);
// Clear the points list.
polylines.clear();
polylinesOverlaid.clear();
super.onPause();
}
@Override
protected void onStop() {
super.onStop();
// Save zoom level in shared preferences
SharedPreferences settings = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putInt(LAST_ZOOM, osmView.getZoomLevel());
editor.apply();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.displaytrackmap_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.displaytrackmap_menu_center_to_gps).setEnabled((!centerToGpsPos && currentPosition != null));
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.displaytrackmap_menu_center_to_gps:
centerToGpsPos = true;
if (currentPosition != null) {
osmViewController.animateTo(currentPosition);
}
break;
case R.id.displaytrackmap_menu_overlay_other:
// Start track picker activity
Intent i = new Intent(this, TrackPicker.class);
i.putExtra(TrackContentProvider.Schema.COL_TRACK_ID, currentTrackId);
i.putExtra(OSMTracker.INTENT_KEY_OVERLAID_TRACK_ID, overlaidTrackId);
startActivityForResult(i, RC_PICK_OVERLAID);
break;
case R.id.displaytrackmap_menu_settings:
// Start settings activity
startActivity(new Intent(this, Preferences.class));
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
if(requestCode == RC_PICK_OVERLAID &&
resultCode == RESULT_OK) {
overlaidTrackId = data.getLongExtra(OSMTracker.INTENT_KEY_OVERLAID_TRACK_ID,0);
final DataHelper dataHelper = new DataHelper(this);
dataHelper.updateOverlay(currentTrackId,overlaidTrackId);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
if (currentPosition != null)
centerToGpsPos = false;
break;
}
return super.onTouchEvent(event);
}
/**
* Creates overlays over the OSM view
*/
private void createOverlays() {
DisplayMetrics metrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(metrics);
// set with to hopefully DPI independent 0.5mm
polylines = new Polylines(Color.BLUE, (float)(metrics.densityDpi / 25.4 / 2), osmView);
polylinesOverlaid = new Polylines(Color.RED, (float)(metrics.densityDpi / 25.4 / 2), osmView);
myLocationOverlay = new SimpleLocationOverlay(this);
osmView.getOverlays().add(myLocationOverlay);
wayPointsOverlay = new WayPointsOverlay(this, currentTrackId);
osmView.getOverlays().add(wayPointsOverlay);
scaleBarOverlay = new ScaleBarOverlay(osmView);
osmView.getOverlays().add(scaleBarOverlay);
}
/**
* On track path changed, update the two overlays and repaint view.
* If {@link #lastTrackPointIdProcessed} is null, this is the initial call
* from {@link #onResume()}, and not the periodic call from
* {@link ContentObserver#onChange(boolean) trackpointContentObserver.onChange(boolean)}
* while recording.
* @param polylines lineset to update
* @param trackId trackid from which to draw lineset
*/
private synchronized void pathChanged(Polylines polylines, long trackId) {
if (isFinishing()) {
return;
}
// See if the track is active.
// If not, we'll calculate initial track bounds
// while retrieving from the database.
// (the first point will overwrite these lat/lon bounds.)
boolean doInitialBoundsCalc = false;
double minLat = 91.0, minLon = 181.0;
double maxLat = -91.0, maxLon = -181.0;
if (trackId == currentTrackId &&
(!zoomedToTrackAlready) && (lastTrackPointIdProcessed == null)) {
final String[] proj_active = {TrackContentProvider.Schema.COL_ACTIVE};
Cursor cursor = getContentResolver().query(
ContentUris.withAppendedId(TrackContentProvider.CONTENT_URI_TRACK, trackId),
proj_active, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int colIndex = cursor.getColumnIndex(TrackContentProvider.Schema.COL_ACTIVE);
if (colIndex != -1) {
doInitialBoundsCalc =
(cursor.getInt(colIndex) == TrackContentProvider.Schema.VAL_TRACK_INACTIVE);
}
cursor.close();
}
}
// Projection: The columns to retrieve. Here, we want the latitude,
// longitude and primary key only
String[] projection = {TrackContentProvider.Schema.COL_LATITUDE, TrackContentProvider.Schema.COL_LONGITUDE, TrackContentProvider.Schema.COL_ID, TrackContentProvider.Schema.COL_SEG_ID };
// Selection: The where clause to use
String selection = null;
// SelectionArgs: The parameter replacements to use for the '?' in the selection
String[] selectionArgs = null;
// Only request the track points that we have not seen yet
// If we have processed any track points in this session then
// lastTrackPointIdProcessed will not be null. We only want
// to see data from rows with a primary key greater than lastTrackPointIdProcessed
if (lastTrackPointIdProcessed != null) {
selection = TrackContentProvider.Schema.COL_ID + " > ?";
List<String> selectionArgsList = new ArrayList<>();
selectionArgsList.add(lastTrackPointIdProcessed.toString());
selectionArgs = selectionArgsList.toArray(new String[1]);
}
// Retrieve any points we have not yet seen
Cursor c = getContentResolver().query(
TrackContentProvider.trackPointsUri(trackId),
projection, selection, selectionArgs, TrackContentProvider.Schema.COL_ID + " asc");
if (c != null) {
int numberOfPointsRetrieved = c.getCount();
if (numberOfPointsRetrieved > 0) {
c.moveToFirst();
double lastLat = 0;
double lastLon = 0;
int primaryKeyColumnIndex = c.getColumnIndex(TrackContentProvider.Schema.COL_ID);
int latitudeColumnIndex = c.getColumnIndex(TrackContentProvider.Schema.COL_LATITUDE);
int longitudeColumnIndex = c.getColumnIndex(TrackContentProvider.Schema.COL_LONGITUDE);
int segmentIdColumnIndex = c.getColumnIndex(TrackContentProvider.Schema.COL_SEG_ID);
// Add each new point to the track
while (!c.isAfterLast()) {
lastLat = c.getDouble(latitudeColumnIndex);
lastLon = c.getDouble(longitudeColumnIndex);
lastTrackPointIdProcessed = c.getInt(primaryKeyColumnIndex);
int segmentId = c.getInt(segmentIdColumnIndex);
if(segmentId != prevSegmentId) {
polylines.nextSegment();
}
prevSegmentId = segmentId;
polylines.addPoint(new GeoPoint(lastLat, lastLon));
if (doInitialBoundsCalc) {
if (lastLat < minLat) minLat = lastLat;
if (lastLon < minLon) minLon = lastLon;
if (lastLat > maxLat) maxLat = lastLat;
if (lastLon > maxLon) maxLon = lastLon;
}
c.moveToNext();
}
// Last point is current position.
currentPosition = new GeoPoint(lastLat, lastLon);
myLocationOverlay.setLocation(currentPosition);
if (centerToGpsPos) {
osmViewController.setCenter(currentPosition);
}
// Repaint
osmView.invalidate();
if (doInitialBoundsCalc && (numberOfPointsRetrieved > 1)) {
// osmdroid-3.0.8 hangs if we directly call zoomToSpan during initial onResume,
// so post a Runnable instead for after it's done initializing.
final double north = maxLat, east = maxLon, south = minLat, west = minLon;
osmView.post(() -> {
osmViewController.zoomToSpan((int) (north - south), (int) (east - west));
osmViewController.setCenter(new GeoPoint((north + south) / 2, (east + west) / 2));
zoomedToTrackAlready = true;
});
}
}
c.close();
}
}
}