/
MapHandler.java
542 lines (484 loc) · 17.1 KB
/
MapHandler.java
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
package com.junjunguo.pocketmaps.map;
import android.app.Activity;
import android.graphics.Path;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.oscim.android.MapView;
import org.oscim.android.canvas.AndroidGraphics;
import org.oscim.backend.canvas.Bitmap;
import org.oscim.core.GeoPoint;
import org.oscim.core.MapPosition;
import org.oscim.event.Gesture;
import org.oscim.event.GestureListener;
import org.oscim.event.MotionEvent;
import org.oscim.layers.Layer;
import org.oscim.layers.vector.PathLayer;
import org.oscim.layers.marker.ItemizedLayer;
import org.oscim.layers.marker.MarkerItem;
import org.oscim.layers.marker.MarkerSymbol;
import org.oscim.layers.tile.buildings.BuildingLayer;
import org.oscim.layers.tile.vector.VectorTileLayer;
import org.oscim.layers.tile.vector.labeling.LabelLayer;
import org.oscim.layers.vector.geometries.Style;
import org.oscim.map.Layers;
import org.oscim.theme.VtmThemes;
import org.oscim.tiling.source.mapfile.MapFileTileSource;
import com.graphhopper.GHRequest;
import com.graphhopper.GHResponse;
import com.graphhopper.GraphHopper;
import com.graphhopper.PathWrapper;
import com.graphhopper.android.GHAsyncTask;
import com.graphhopper.util.Constants;
import com.graphhopper.util.StopWatch;
import com.graphhopper.util.Parameters.Algorithms;
import com.graphhopper.util.Parameters.Routing;
import com.graphhopper.util.PointList;
import com.junjunguo.pocketmaps.R;
import com.junjunguo.pocketmaps.model.listeners.MapHandlerListener;
import com.junjunguo.pocketmaps.navigator.NaviEngine;
import com.junjunguo.pocketmaps.util.TargetDirComputer;
import com.junjunguo.pocketmaps.util.Variable;
public class MapHandler
{
private static MapHandler mapHandler;
private volatile boolean prepareInProgress = false;
private volatile boolean calcPathActive = false;
MapPosition tmpPos = new MapPosition();
private GeoPoint startMarker;
private GeoPoint endMarker;
private boolean needLocation = false;
private Activity activity;
private MapView mapView;
private ItemizedLayer<MarkerItem> itemizedLayer;
private ItemizedLayer<MarkerItem> customLayer;
private PathLayer pathLayer;
private PathLayer polylineTrack;
private GraphHopper hopper;
private MapHandlerListener mapHandlerListener;
private String currentArea;
File mapsFolder;
PointList trackingPointList;
private int customIcon = R.drawable.ic_my_location_dark_24dp;
private MapFileTileSource tileSource;
/**
* need to know if path calculating status change; this will trigger MapActions function
*/
private boolean needPathCal;
public static MapHandler getMapHandler()
{
if (mapHandler == null)
{
reset();
}
return mapHandler;
}
/**
* reset class, build a new instance
*/
public static void reset()
{
mapHandler = new MapHandler();
}
private MapHandler()
{
setCalculatePath(false,false);
startMarker = null;
endMarker = null;
// polylinePath = null;
needLocation = false;
needPathCal = false;
}
public void init(Activity activity, MapView mapView, String currentArea, File mapsFolder)
{
this.activity = activity;
this.mapView = mapView;
this.currentArea = currentArea;
this.mapsFolder = mapsFolder; // path/to/map/area-gh/
}
public MapFileTileSource getTileSource() { return tileSource; }
/**
* load map to mapView
*
* @param areaFolder
*/
public void loadMap(File areaFolder)
{
logUser("loading map");
// Map events receiver
mapView.map().layers().add(new MapEventsReceiver(mapView.map()));
// Map file source
tileSource = new MapFileTileSource();
tileSource.setMapFile(new File(areaFolder, currentArea + ".map").getAbsolutePath());
VectorTileLayer l = mapView.map().setBaseMap(tileSource);
mapView.map().setTheme(VtmThemes.DEFAULT);
mapView.map().layers().add(new BuildingLayer(mapView.map(), l));
mapView.map().layers().add(new LabelLayer(mapView.map(), l));
// Markers layer
itemizedLayer = new ItemizedLayer<>(mapView.map(), (MarkerSymbol) null);
mapView.map().layers().add(itemizedLayer);
customLayer = new ItemizedLayer<>(mapView.map(), (MarkerSymbol) null);
mapView.map().layers().add(customLayer);
// Map position
GeoPoint mapCenter = tileSource.getMapInfo().boundingBox.getCenterPoint();
mapView.map().setMapPosition(mapCenter.getLatitude(), mapCenter.getLongitude(), 1 << 12);
// GuiMenu.getInstance().showMap(this);
// setContentView(mapView);
ViewGroup.LayoutParams params =
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
activity.addContentView(mapView, params);
loadGraphStorage();
}
void loadGraphStorage() {
logUser("loading graph (" + Constants.VERSION + ") ... ");
new GHAsyncTask<Void, Void, Path>() {
protected Path saveDoInBackground(Void... v) throws Exception {
GraphHopper tmpHopp = new GraphHopper().forMobile();
// Why is "shortest" missing in default config? Add!
tmpHopp.getCHFactoryDecorator().addWeighting("shortest");
tmpHopp.load(new File(mapsFolder, currentArea).getAbsolutePath() + "-gh");
log("found graph " + tmpHopp.getGraphHopperStorage().toString() + ", nodes:" + tmpHopp.getGraphHopperStorage().getNodes());
hopper = tmpHopp;
return null;
}
protected void onPostExecute(Path o) {
if (hasError()) {
logUser("An error happened while creating graph:"
+ getErrorMessage());
} else {
logUser("Finished loading graph.");
}
prepareInProgress = false;
}
}.execute();
}
/**
* center the LatLong point in the map and zoom map to zoomLevel
*
* @param latLong
* @param zoomLevel (if 0 use current zoomlevel)
*/
public void centerPointOnMap(GeoPoint latLong, int zoomLevel, float bearing, float tilt)
{
if (zoomLevel == 0)
{
zoomLevel = mapView.map().getMapPosition().zoomLevel;
}
log("Using cur zoom: " + zoomLevel);
double scale = 1 << zoomLevel;
tmpPos.setPosition(latLong);
tmpPos.setScale(scale);
tmpPos.setBearing(bearing);
tmpPos.setTilt(tilt);
mapView.map().animator().animateTo(300, tmpPos);
}
/**
* @return
*/
public boolean isNeedLocation()
{
return needLocation;
}
/**
* set in need a location from screen point (touch)
*
* @param needLocation
*/
public void setNeedLocation(boolean needLocation)
{
this.needLocation = needLocation;
}
/** Set start or end Point-Marker.
* @param p The Point to set, or null.
* @param isStart True for startpoint false for endpoint.
* @param recalculate True to calculate path, when booth points are set.
* @return Whether the path will be recalculated. **/
public boolean setStartEndPoint(GeoPoint p, boolean isStart, boolean recalculate)
{
boolean result = false;
boolean refreshBoth = false;
if (startMarker!=null && endMarker!=null && p!=null) { refreshBoth = true; }
if (isStart)
{
startMarker = p;
}
else { endMarker = p; }
// remove routing layers
if ((startMarker==null || endMarker==null) || refreshBoth)
{
if (pathLayer!=null) { pathLayer.clearPath(); }
itemizedLayer.removeAllItems();
}
if (startMarker!=null)
{
itemizedLayer.addItem(createMarkerItem(startMarker, R.drawable.ic_location_start_24dp, 0.5f, 1.0f));
}
if (endMarker!=null)
{
itemizedLayer.addItem(createMarkerItem(endMarker, R.drawable.ic_location_end_24dp, 0.5f, 1.0f));
}
if (startMarker!=null && endMarker!=null && recalculate)
{
recalcPath();
result = true;
}
mapView.map().updateMap(true);
return result;
}
public void recalcPath()
{
setCalculatePath(true, true);
calcPath(startMarker.getLatitude(), startMarker.getLongitude(), endMarker.getLatitude(), endMarker.getLongitude());
}
/** Set the custom Point for current location, or null to delete.
* Sets the offset to center. **/
public void setCustomPoint(GeoPoint p)
{
customLayer.removeAllItems();
if (p!=null)
{
customLayer.addItem(createMarkerItem(p,customIcon, 0.5f, 0.5f));
mapView.map().updateMap(true);
}
}
public void setCustomPointIcon(int customIcon)
{
this.customIcon = customIcon;
if (customLayer.getItemList().size() > 0)
{ // RefreshIcon
MarkerItem curSymbol = customLayer.getItemList().get(0);
MarkerSymbol marker = createMarkerItem(new GeoPoint(0,0), customIcon, 0.5f, 0.5f).getMarker();
curSymbol.setMarker(marker);
}
}
private MarkerItem createMarkerItem(GeoPoint p, int resource, float offsetX, float offsetY) {
// Drawable drawable = activity.getDrawable(resource); // Since API21
Drawable drawable = ContextCompat.getDrawable(activity, resource);
Bitmap bitmap = AndroidGraphics.drawableToBitmap(drawable);
MarkerSymbol markerSymbol = new MarkerSymbol(bitmap, offsetX, offsetY);
MarkerItem markerItem = new MarkerItem("", "", p);
markerItem.setMarker(markerSymbol);
return markerItem;
}
/**
* remove all markers and polyline from layers
*/
public void removeMarkers() {
// setCustomPoint(null, 0);
setStartEndPoint(null, true, false);
setStartEndPoint(null, false, false);
}
/**
* @return true if already loaded
*/
boolean isReady() {
return !prepareInProgress;
}
/**
* start tracking : reset polylineTrack & trackingPointList & remove polylineTrack if exist
*/
public void startTrack() {
if (polylineTrack != null) {
removeLayer(mapView.map().layers(), polylineTrack);
}
polylineTrack = null;
trackingPointList = new PointList();
if (polylineTrack != null) { polylineTrack.clearPath(); }
polylineTrack = updatePathLayer(polylineTrack, trackingPointList, 0x99003399, 4);
NaviEngine.getNaviEngine().startDebugSimulator(activity, true);
}
/**
* add a tracking point
*
* @param point
*/
public void addTrackPoint(GeoPoint point) {
trackingPointList.add(point.getLatitude(), point.getLongitude());
updatePathLayer(polylineTrack, trackingPointList, 0x9900cc33, 4);
mapView.map().updateMap(true);
}
/**
* remove a layer from map layers
*
* @param layers
* @param layer
*/
public static void removeLayer(Layers layers, Layer layer)
{
if (layers != null && layer != null && layers.contains(layer))
{
layers.remove(layer);
}
}
public boolean isCalculatingPath() {
return calcPathActive;
}
private void setCalculatePath(boolean calcPathActive, boolean callListener) {
this.calcPathActive = calcPathActive;
if (mapHandlerListener != null && needPathCal && callListener) mapHandlerListener.pathCalculating(calcPathActive);
}
public void setNeedPathCal(boolean needPathCal) {
this.needPathCal = needPathCal;
}
/**
* @return GraphHopper object
*/
public GraphHopper getHopper() {
return hopper;
}
/**
* assign a new GraphHopper
*
* @param hopper
*/
public void setHopper(GraphHopper hopper) {
this.hopper = hopper;
}
/**
* only tell on object
*
* @param mapHandlerListener
*/
public void setMapHandlerListener(MapHandlerListener mapHandlerListener) {
this.mapHandlerListener = mapHandlerListener;
}
public Activity getActivity() {
return activity;
}
public void calcPath(final double fromLat, final double fromLon,
final double toLat, final double toLon) {
setCalculatePath(true, false);
log("calculating path ...");
new AsyncTask<Void, Void, GHResponse>() {
float time;
@Override
protected GHResponse doInBackground(Void... v) {
StopWatch sw = new StopWatch().start();
GHRequest req = new GHRequest(fromLat, fromLon, toLat, toLon).
setAlgorithm(Algorithms.DIJKSTRA_BI);
req.getHints().put(Routing.INSTRUCTIONS, Variable.getVariable().getDirectionsON());
req.setVehicle(Variable.getVariable().getTravelMode().toString().toLowerCase());
req.setWeighting(Variable.getVariable().getWeighting());
GHResponse resp = hopper.route(req);
if (resp.hasErrors())
{
NaviEngine.getNaviEngine().setDirectTargetDir(true);
List<Throwable> errors = resp.getErrors();
log("Multible errors, first: " + errors.get(0));
resp = TargetDirComputer.getInstance().createTargetdirResponse(fromLat, fromLon, toLat, toLon);
}
else
{
NaviEngine.getNaviEngine().setDirectTargetDir(false);
}
time = sw.stop().getSeconds();
return resp;
}
@Override
protected void onPostExecute(GHResponse ghResp) {
if (!ghResp.hasErrors()) {
PathWrapper resp = ghResp.getBest();
log("from:" + fromLat + "," + fromLon + " to:" + toLat + ","
+ toLon + " found path with distance:" + resp.getDistance()
/ 1000f + ", nodes:" + resp.getPoints().getSize() + ", time:"
+ time + " " + resp.getDebugInfo());
logUser("the route is " + (int) (resp.getDistance() / 100) / 10f
+ "km long, time:" + resp.getTime() / 60000f + "min.");
int sWidth = 4;
pathLayer = updatePathLayer(pathLayer, resp.getPoints(), 0x9900cc33, sWidth);
mapView.map().updateMap(true);
if (Variable.getVariable().isDirectionsON()) {
Navigator.getNavigator().setGhResponse(resp);
}
} else {
logUser("Multible errors: " + ghResp.getErrors().size());
log("Multible errors, first: " + ghResp.getErrors().get(0));
}
if (NaviEngine.getNaviEngine().isNavigating())
{
setCalculatePath(false, false);
}
else
{
setCalculatePath(false, true);
try
{
activity.findViewById(R.id.map_nav_settings_path_finding).setVisibility(View.GONE);
activity.findViewById(R.id.nav_settings_layout).setVisibility(View.VISIBLE);
}
catch (Exception e) { e.printStackTrace(); }
}
}
}.execute();
}
private PathLayer updatePathLayer(PathLayer ref, PointList pointList, int color, int strokeWidth) {
if (ref==null) {
ref = createPathLayer(color, strokeWidth);
mapView.map().layers().add(ref);
}
List<GeoPoint> geoPoints = new ArrayList<>();
//TODO: Search for a more efficient way
for (int i = 0; i < pointList.getSize(); i++)
geoPoints.add(new GeoPoint(pointList.getLatitude(i), pointList.getLongitude(i)));
ref.setPoints(geoPoints);
return ref;
}
public void joinPathLayerToPos(double lat, double lon)
{
try
{
List<GeoPoint> geoPoints = new ArrayList<>();
geoPoints.add(new GeoPoint(lat,lon));
geoPoints.add(pathLayer.getPoints().get(1));
pathLayer.setPoints(geoPoints);
}
catch (Exception e) { log("Error: " + e); }
}
private PathLayer createPathLayer(int color, int strokeWidth)
{
Style style = Style.builder()
.fixed(true)
.generalization(Style.GENERALIZATION_SMALL)
.strokeColor(color)
.strokeWidth(strokeWidth * activity.getResources().getDisplayMetrics().density)
.build();
PathLayer newPathLayer = new PathLayer(mapView.map(), style);
return newPathLayer;
}
class MapEventsReceiver extends Layer implements GestureListener {
MapEventsReceiver(org.oscim.map.Map map) {
super(map);
}
@Override
public boolean onGesture(Gesture g, MotionEvent e) {
if (g instanceof Gesture.Tap) {
GeoPoint p = mMap.viewport().fromScreenPoint(e.getX(), e.getY());
if (mapHandlerListener!=null && needLocation)
{
mapHandlerListener.onPressLocation(p);
}
}
return false;
}
}
private void logUser(String str)
{
log(str);
try
{
Toast.makeText(activity, str, Toast.LENGTH_LONG).show();
}
catch (Exception e) { e.printStackTrace(); }
}
private void log(String str)
{
Log.i(MapHandler.class.getName(), str);
}
}