-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWPCacheManager.java
More file actions
850 lines (729 loc) · 38 KB
/
WPCacheManager.java
File metadata and controls
850 lines (729 loc) · 38 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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
package com.example;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Point;
import android.location.Location;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import org.osmdroid.api.IMapView;
import org.osmdroid.tileprovider.MapTile;
import org.osmdroid.tileprovider.MapTileProviderBase;
import org.osmdroid.tileprovider.constants.BonusPackHelper;
import org.osmdroid.tileprovider.constants.OpenStreetMapTileProviderConstants;
import org.osmdroid.tileprovider.modules.TileWriter;
import org.osmdroid.tileprovider.tilesource.ITileSource;
import org.osmdroid.tileprovider.tilesource.OnlineTileSourceBase;
import org.osmdroid.tileprovider.util.StreamUtils;
import org.osmdroid.util.BoundingBoxE6;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.util.MyMath;
import org.osmdroid.util.TileSystem;
import org.osmdroid.views.MapView;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
;
/**
* Provides various methods for managing the local filesystem cache of osmdroid tiles: <br>
* - Dowloading of tiles inside a specified area, <br>
* - Cleaning of tiles inside a specified area,<br>
* - Information about cache capacity and current cache usage. <br>
* <p/>
* Important note 1: <br>
* These methods only make sense for a MapView using an OnlineTileSourceBase:
* bitmap tiles downloaded from urls. <br>
* <p/>
* Important note 2 - about Bulk Downloading:<br>
* When using OSM Mapnik tile server as the tile source, take care about OSM Tile usage policy
* (http://wiki.openstreetmap.org/wiki/Tile_usage_policy).
* Do not let to end-users the ability to download significant areas of tiles. <br>
*
* @author M.Kergall
*/
public class WPCacheManager {
protected final MapTileProviderBase mTileProvider;
protected final TileWriter mTileWriter;
protected final MapView mMapView;
static final double EARTH_RADIUS_IN_METERS = 6371000.0; //meters
public WPCacheManager(final MapView mapView) {
mTileProvider = mapView.getTileProvider();
mTileWriter = new TileWriter();
mMapView = mapView;
}
public Point getMapTileFromCoordinates(final double aLat, final double aLon, final int zoom) {
final int y = (int) Math.floor((1 - Math.log(Math.tan(aLat * Math.PI / 180) + 1 / Math.cos(aLat * Math.PI / 180)) / Math.PI) / 2 * (1 << zoom));
final int x = (int) Math.floor((aLon + 180) / 360 * (1 << zoom));
return new Point(x, y);
}
public GeoPoint getCoordinatesFromMapTile(final int x, final int y, final int zoom) {
double n = Math.PI - 2 * Math.PI * y / (1 << zoom);
final double lat = (180 / Math.PI * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))));
final double lon = (360.0 * x / (1 << zoom)) - 180.0;
return new GeoPoint(lat, lon);
}
public File getFileName(ITileSource tileSource, MapTile tile) {
final File file = new File(OpenStreetMapTileProviderConstants.TILE_PATH_BASE,
tileSource.getTileRelativeFilenameString(tile) + OpenStreetMapTileProviderConstants.TILE_PATH_EXTENSION);
return file;
}
/**
* @return true if success, false if error
*/
public boolean loadTile(OnlineTileSourceBase tileSource, MapTile tile) {
//check if file is already downloaded:
File file = getFileName(tileSource, tile);
if (file.exists()) {
return true;
}
InputStream in = null;
OutputStream out = null;
HttpURLConnection urlConnection = null;
try {
final String tileURLString = tileSource.getTileURLString(tile);
urlConnection = (HttpURLConnection) new URL(tileURLString).openConnection();
// Check to see if we got success
if (urlConnection.getResponseCode() != 200) {
Log.w(BonusPackHelper.LOG_TAG, "Problem downloading MapTile: " + tile + " HTTP response: " + urlConnection.getResponseMessage());
return false;
}
in = urlConnection.getInputStream();
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, StreamUtils.IO_BUFFER_SIZE);
StreamUtils.copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
final ByteArrayInputStream byteStream = new ByteArrayInputStream(data);
// Save the data to the filesystem cache
mTileWriter.saveFile(tileSource, tile, byteStream);
byteStream.reset();
//final Drawable result = tileSource.getDrawable(byteStream);
return true;
} catch (final UnknownHostException e) {
// no network connection
Log.w(BonusPackHelper.LOG_TAG, "UnknownHostException downloading MapTile: " + tile + " : " + e);
} catch (final FileNotFoundException e) {
Log.w(BonusPackHelper.LOG_TAG, "Tile not found: " + tile + " : " + e);
} catch (final IOException e) {
Log.w(BonusPackHelper.LOG_TAG, "IOException downloading MapTile: " + tile + " : " + e);
} catch (final Throwable e) {
Log.e(BonusPackHelper.LOG_TAG, "Error downloading MapTile: " + tile, e);
} finally {
StreamUtils.closeStream(in);
StreamUtils.closeStream(out);
if (urlConnection != null) {
urlConnection.disconnect();
}
urlConnection = null;
}
return false;
}
/**
* @return the theoretical number of tiles in the specified area
*/
public int possibleTilesInArea(BoundingBoxE6 bb, final int zoomMin, final int zoomMax) {
int total = 0;
for (int zoomLevel = zoomMin; zoomLevel <= zoomMax; zoomLevel++) {
Point mLowerRight = getMapTileFromCoordinates(bb.getLatSouthE6() * 1E-6, bb.getLonEastE6() * 1E-6, zoomLevel);
Point mUpperLeft = getMapTileFromCoordinates(bb.getLatNorthE6() * 1E-6, bb.getLonWestE6() * 1E-6, zoomLevel);
int y = mLowerRight.y - mUpperLeft.y + 1;
int x = mLowerRight.x - mUpperLeft.x + 1;
int nbTilesForZoomLevel = x * y;
total += nbTilesForZoomLevel;
}
return total;
}
/**
* @return the theoretical number of tiles covered by the list of points
* Calculation done based on http://www.movable-type.co.uk/scripts/latlong.html
*/
public int possibleTilesCovered(ArrayList<GeoPoint> geoPoints, final int zoomMin, final int zoomMax) {
ArrayList<Point> tilePoints = new ArrayList<>();
boolean foundTilePoint;
GeoPoint prevPoint = null, wayPoint;
double d, leadCoef, brng, latRad, lonRad, prevLatRad, prevLonRad;
Point tile, prevTile = null, lastPoint;
for (int zoomLevel = zoomMin; zoomLevel <= zoomMax; zoomLevel++) {
for (GeoPoint geoPoint : geoPoints) {
d = TileSystem.GroundResolution(geoPoint.getLatitude(), zoomLevel);
if (tilePoints.size() != 0) {
if (prevPoint != null) {
leadCoef = (geoPoint.getLatitude() - prevPoint.getLatitude()) / (geoPoint.getLongitude() - prevPoint.getLongitude());
if (geoPoint.getLongitude() > prevPoint.getLongitude()) {
brng = Math.PI / 2 - Math.atan(leadCoef);
} else {
brng = 3 * Math.PI / 2 - Math.atan(leadCoef);
}
wayPoint = new GeoPoint(prevPoint.getLatitude(), prevPoint.getLongitude());
while ((((geoPoint.getLatitude() > prevPoint.getLatitude()) && (wayPoint.getLatitude() < geoPoint.getLatitude())) ||
(geoPoint.getLatitude() < prevPoint.getLatitude()) && (wayPoint.getLatitude() > geoPoint.getLatitude())) &&
(((geoPoint.getLongitude() > prevPoint.getLongitude()) && (wayPoint.getLongitude() < geoPoint.getLongitude())) ||
((geoPoint.getLongitude() < prevPoint.getLongitude()) && (wayPoint.getLongitude() > geoPoint.getLongitude())))) {
lastPoint = new Point();
TileSystem.LatLongToPixelXY(geoPoint.getLatitude(), geoPoint.getLongitude(), zoomLevel, lastPoint);
prevLatRad = wayPoint.getLatitude() * Math.PI / 180.0;
prevLonRad = wayPoint.getLongitude() * Math.PI / 180.0;
latRad = Math.asin(Math.sin(prevLatRad) * Math.cos(d / EARTH_RADIUS_IN_METERS) + Math.cos(prevLatRad) * Math.sin(d / EARTH_RADIUS_IN_METERS) * Math.cos(brng));
lonRad = prevLonRad + Math.atan2(Math.sin(brng) * Math.sin(d / EARTH_RADIUS_IN_METERS) * Math.cos(prevLatRad), Math.cos(d / EARTH_RADIUS_IN_METERS) - Math.sin(prevLatRad) * Math.sin(latRad));
wayPoint.setLatitudeE6((int) ((latRad * 180.0 / Math.PI) * 1E6));
wayPoint.setLongitudeE6((int) ((lonRad * 180.0 / Math.PI) * 1E6));
tile = getMapTileFromCoordinates(wayPoint.getLatitude(), wayPoint.getLongitude(), zoomLevel);
if (!tile.equals(prevTile)) {
//Log.d(Constants.APP_TAG, "New Tile lat " + tile.x + " lon " + tile.y);
int ofsx = tile.x >= 0 ? 0 : -tile.x;
int ofsy = tile.y >= 0 ? 0 : -tile.y;
for (int xAround = tile.x + ofsx; xAround <= tile.x + 1 + ofsx; xAround++) {
for (int yAround = tile.y + ofsy; yAround <= tile.y + 1 + ofsy; yAround++) {
Point tileAround = new Point(xAround, yAround);
foundTilePoint = false;
for (Point inList : tilePoints) {
if (tileAround.equals(inList.x, inList.y)) {
foundTilePoint = true;
break;
}
}
if (!foundTilePoint) {
tilePoints.add(0, tileAround);
}
}
}
prevTile = tile;
}
}
}
} else {
tile = getMapTileFromCoordinates(geoPoint.getLatitude(), geoPoint.getLongitude(), zoomLevel);
prevTile = tile;
int ofsx = tile.x >= 0 ? 0 : -tile.x;
int ofsy = tile.y >= 0 ? 0 : -tile.y;
for (int xAround = tile.x + ofsx; xAround <= tile.x + 1 + ofsx; xAround++) {
for (int yAround = tile.y + ofsy; yAround <= tile.y + 1 + ofsy; yAround++) {
Point tileAround = new Point(xAround, yAround);
tilePoints.add(0, tileAround);
}
}
}
prevPoint = geoPoint;
}
}
Log.d(Constants.APP_TAG, "need " + tilePoints.size() + " Tiles");
return tilePoints.size();
}
protected String zoomMessage(int zoomLevel, int zoomMin, int zoomMax) {
return "Handling zoom level: " + zoomLevel + " (from " + zoomMin + " to " + zoomMax + ")";
}
/**
* Download in background all tiles of the specified area in osmdroid cache.
*
* @param ctx
* @param bb
* @param zoomMin
* @param zoomMax
*/
public void downloadAreaAsync(Context ctx, BoundingBoxE6 bb, final int zoomMin, final int zoomMax) {
new DownloadingTask(ctx, bb, zoomMin, zoomMax, null, true).execute();
}
/**
* Download in background all tiles of the specified area in osmdroid cache.
*
* @param ctx
* @param geoPoints
* @param zoomMin
* @param zoomMax
*/
public void downloadAreaAsync(Context ctx, ArrayList<GeoPoint> geoPoints, final int zoomMin, final int zoomMax) {
new DownloadingTask(ctx, geoPoints, zoomMin, zoomMax, null, true).execute();
}
/**
* Download in background all tiles of the specified area in osmdroid cache.
*
* @param ctx
* @param bb
* @param zoomMin
* @param zoomMax
*/
public void downloadAreaAsync(Context ctx, BoundingBoxE6 bb, final int zoomMin, final int zoomMax, final CacheManagerCallback callback) {
new DownloadingTask(ctx, bb, zoomMin, zoomMax, callback, true).execute();
}
/**
* Download in background all tiles covered by the GePoints list in osmdroid cache.
*
* @param ctx
* @param geoPoints
* @param zoomMin
* @param zoomMax
*/
public void downloadAreaAsync(Context ctx, ArrayList<GeoPoint> geoPoints, final int zoomMin, final int zoomMax, final CacheManagerCallback callback) {
new DownloadingTask(ctx, geoPoints, zoomMin, zoomMax, callback, true).execute();
}
/**
* Download in background all tiles of the specified area in osmdroid cache without a user interface.
*
* @param ctx
* @param bb
* @param zoomMin
* @param zoomMax
* @since 5.3
*/
public void downloadAreaAsyncNoUI(Context ctx, BoundingBoxE6 bb, final int zoomMin, final int zoomMax, final CacheManagerCallback callback) {
new DownloadingTask(ctx, bb, zoomMin, zoomMax, callback, false).execute();
}
/**
* Download in background all tiles covered by the GeoPoints list in osmdroid cache without a user interface.
*
* @param ctx
* @param geoPoints
* @param zoomMin
* @param zoomMax
* @since
*/
public void downloadAreaAsyncNoUI(Context ctx, ArrayList<GeoPoint> geoPoints, final int zoomMin, final int zoomMax, final CacheManagerCallback callback) {
new DownloadingTask(ctx, geoPoints, zoomMin, zoomMax, callback, false).execute();
}
/**
*
*/
public interface CacheManagerCallback {
/**
* fired when the download job is done.
*/
public void onTaskComplete();
/**
* this is fired periodically, useful for updating dialogs, progress bars, etc
*
* @param progress
* @param currentZoomLevel
* @param zoomMin
* @param zoomMax
*/
public void updateProgress(int progress, int currentZoomLevel, int zoomMin, int zoomMax);
/**
* as soon as the download is started, this is fired
*/
public void downloadStarted();
/**
* this is fired right before the download starts
*
* @param total
*/
public void setPossibleTilesInArea(int total);
void onTaskFailed();
}
/**
* generic class for common code related to AsyncTask management
*/
protected abstract class CacheManagerTask extends AsyncTask<Object, Integer, Integer> {
ProgressDialog mProgressDialog;
boolean showUI = true;
int mZoomMin, mZoomMax;
BoundingBoxE6 mBB;
ArrayList<GeoPoint> mGeoPoints;
Context mCtx;
CacheManagerCallback callback = null;
public CacheManagerTask(Context pCtx, BoundingBoxE6 pBB, final int pZoomMin, final int pZoomMax, final CacheManagerCallback callback, final boolean showUI) {
this(pCtx, pBB, pZoomMin, pZoomMax);
this.callback = callback;
this.showUI = showUI;
}
public CacheManagerTask(Context pCtx, ArrayList<GeoPoint> geoPoints, final int pZoomMin, final int pZoomMax, final CacheManagerCallback callback, final boolean showUI) {
this(pCtx, geoPoints, pZoomMin, pZoomMax);
this.callback = callback;
this.showUI = showUI;
this.mGeoPoints = geoPoints;
}
public CacheManagerTask(Context pCtx, BoundingBoxE6 pBB, final int pZoomMin, final int pZoomMax) {
mCtx = pCtx;
mBB = pBB;
mZoomMin = Math.max(pZoomMin, mMapView.getMinZoomLevel());
mZoomMax = Math.min(pZoomMax, mMapView.getMaxZoomLevel());
}
public CacheManagerTask(Context pCtx, ArrayList<GeoPoint> pGeoPoints, final int pZoomMin, final int pZoomMax) {
mCtx = pCtx;
mGeoPoints = pGeoPoints;
mZoomMin = Math.max(pZoomMin, mMapView.getMinZoomLevel());
mZoomMax = Math.min(pZoomMax, mMapView.getMaxZoomLevel());
}
protected ProgressDialog createProgressDialog(Context pCtx) {
ProgressDialog pd = new ProgressDialog(pCtx);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(true);
pd.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
cancel(true);
}
});
return pd;
}
@Override
protected void onProgressUpdate(final Integer... count) {
//count[0] = tile counter, count[1] = current zoom level
if (showUI) {
mProgressDialog.setProgress(count[0]);
mProgressDialog.setMessage(zoomMessage(count[1], mZoomMin, mZoomMax));
}
if (callback != null) {
try {
callback.updateProgress(count[0], count[1], mZoomMin, mZoomMax);
} catch (Throwable t) {
Log.w(IMapView.LOGTAG, "Error caught processing cachemanager callback, your implementation is faulty", t);
}
}
}
}
protected class DownloadingTask extends CacheManagerTask {
public DownloadingTask(Context pCtx, BoundingBoxE6 pBB, final int pZoomMin, final int pZoomMax, final CacheManagerCallback callback, final boolean showUI) {
super(pCtx, pBB, pZoomMin, pZoomMax, callback, showUI);
}
public DownloadingTask(Context pCtx, ArrayList<GeoPoint> pPoints, final int pZoomMin, final int pZoomMax, final CacheManagerCallback callback, final boolean showUI) {
super(pCtx, pPoints, pZoomMin, pZoomMax, callback, showUI);
}
@Override
protected void onPreExecute() {
int total = 0;
if (mBB != null) {
total = possibleTilesInArea(mBB, mZoomMin, mZoomMax);
} else if (mGeoPoints != null) {
total = possibleTilesCovered(mGeoPoints, mZoomMin, mZoomMax);
}
if (showUI) {
mProgressDialog = createProgressDialog(mCtx);
mProgressDialog.setTitle("Downloading tiles");
mProgressDialog.setMessage(zoomMessage(mZoomMin, mZoomMin, mZoomMax));
mProgressDialog.setMax(total);
mProgressDialog.show();
}
if (callback != null) {
try {
callback.setPossibleTilesInArea(total);
callback.downloadStarted();
} catch (Throwable t) {
Log.w(IMapView.LOGTAG, "Error caught processing cachemanager callback, your implementation is faulty", t);
}
}
}
@Override
protected void onPostExecute(final Integer errors) {
if (showUI) {
if (errors != 0) {
Toast.makeText(mCtx, "Loading completed with " + errors + " errors.", Toast.LENGTH_SHORT).show();
}
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
if (callback != null) {
try {
if (errors == 0) {
callback.onTaskComplete();
} else {
callback.onTaskFailed();
}
} catch (Throwable t) {
Log.w(IMapView.LOGTAG, "Error caught processing cachemanager callback, your implementation is faulty", t);
}
}
}
@Override
protected Integer doInBackground(Object... params) {
int errors = downloadArea();
return errors;
}
/**
* Do the job. No attempt to
*
* @return the number of loading errors.
*/
protected int downloadArea() {
OnlineTileSourceBase tileSource;
if (mTileProvider.getTileSource() instanceof OnlineTileSourceBase) {
tileSource = (OnlineTileSourceBase) mTileProvider.getTileSource();
} else {
Log.e(BonusPackHelper.LOG_TAG, "TileSource is not an online tile source");
return 0;
}
int tileCounter = 0;
int errors = 0;
if (mBB != null) {
for (int zoomLevel = mZoomMin; zoomLevel <= mZoomMax; zoomLevel++) {
Point mLowerRight = getMapTileFromCoordinates(mBB.getLatSouthE6() * 1E-6, mBB.getLonEastE6() * 1E-6, zoomLevel);
Point mUpperLeft = getMapTileFromCoordinates(mBB.getLatNorthE6() * 1E-6, mBB.getLonWestE6() * 1E-6, zoomLevel);
final int mapTileUpperBound = 1 << zoomLevel;
//Get all the MapTiles from the upper left to the lower right:
for (int y = mUpperLeft.y; y <= mLowerRight.y; y++) {
for (int x = mUpperLeft.x; x <= mLowerRight.x; x++) {
final int tileY = MyMath.mod(y, mapTileUpperBound);
final int tileX = MyMath.mod(x, mapTileUpperBound);
final MapTile tile = new MapTile(zoomLevel, tileX, tileY);
//Drawable currentMapTile = mTileProvider.getMapTile(tile);
boolean ok = loadTile(tileSource, tile);
if (!ok) {
errors++;
}
tileCounter++;
if (tileCounter % 10 == 0) {
if (isCancelled()) {
return errors;
}
publishProgress(tileCounter, zoomLevel);
}
}
}
}
} else if (mGeoPoints != null) {
GeoPoint prevPoint = null, wayPoint;
double d, leadCoef, brng, latRad, lonRad, prevLatRad, prevLonRad;
Point tile, prevTile = null, lastPoint;
ArrayList<Point> tilePoints = new ArrayList<>();
boolean foundTilePoint;
for (int zoomLevel = mZoomMin; zoomLevel <= mZoomMax; zoomLevel++) {
final int mapTileUpperBound = 1 << zoomLevel;
for (GeoPoint geoPoint : mGeoPoints) {
d = TileSystem.GroundResolution(geoPoint.getLatitude(), zoomLevel);
if (tileCounter != 0) {
if (prevPoint != null) {
leadCoef = (geoPoint.getLatitude() - prevPoint.getLatitude()) / (geoPoint.getLongitude() - prevPoint.getLongitude());
if (geoPoint.getLongitude() > prevPoint.getLongitude()) {
brng = Math.PI / 2 - Math.atan(leadCoef);
} else {
brng = 3 * Math.PI / 2 - Math.atan(leadCoef);
}
wayPoint = new GeoPoint(prevPoint.getLatitude(), prevPoint.getLongitude());
while ((((geoPoint.getLatitude() > prevPoint.getLatitude()) && (wayPoint.getLatitude() < geoPoint.getLatitude())) ||
(geoPoint.getLatitude() < prevPoint.getLatitude()) && (wayPoint.getLatitude() > geoPoint.getLatitude())) &&
(((geoPoint.getLongitude() > prevPoint.getLongitude()) && (wayPoint.getLongitude() < geoPoint.getLongitude())) ||
((geoPoint.getLongitude() < prevPoint.getLongitude()) && (wayPoint.getLongitude() > geoPoint.getLongitude())))) {
lastPoint = new Point();
TileSystem.LatLongToPixelXY(geoPoint.getLatitude(), geoPoint.getLongitude(), zoomLevel, lastPoint);
prevLatRad = wayPoint.getLatitude() * Math.PI / 180.0;
prevLonRad = wayPoint.getLongitude() * Math.PI / 180.0;
latRad = Math.asin(Math.sin(prevLatRad) * Math.cos(d / EARTH_RADIUS_IN_METERS) + Math.cos(prevLatRad) * Math.sin(d / EARTH_RADIUS_IN_METERS) * Math.cos(brng));
lonRad = prevLonRad + Math.atan2(Math.sin(brng) * Math.sin(d / EARTH_RADIUS_IN_METERS) * Math.cos(prevLatRad), Math.cos(d / EARTH_RADIUS_IN_METERS) - Math.sin(prevLatRad) * Math.sin(latRad));
wayPoint.setLatitudeE6((int)((latRad * 180.0 / Math.PI)* 1E6));
wayPoint.setLongitudeE6((int)((lonRad * 180.0 / Math.PI) * 1E6));
tile = getMapTileFromCoordinates(wayPoint.getLatitude(), wayPoint.getLongitude(), zoomLevel);
if (!tile.equals(prevTile)) {
//Log.d(Constants.APP_TAG, "New Tile lat " + tile.x + " lon " + tile.y);
int ofsx = tile.x >= 0 ? 0 : -tile.x;
int ofsy = tile.y >= 0 ? 0 : -tile.y;
for (int xAround = tile.x + ofsx; xAround <= tile.x + 1 + ofsx; xAround++) {
for (int yAround = tile.y + ofsy; yAround <= tile.y + 1 + ofsy; yAround++) {
Point tileAround = new Point(xAround, yAround);
foundTilePoint = false;
/**
* The following is only necessary to correctly update progress
* as we cannot know if a tile is already downloaded or not.
* Normally loadTile() will only download a tile if necessary
*/
for (Point inList : tilePoints) {
if (tileAround.equals(inList.x, inList.y)) {
foundTilePoint = true;
break;
}
}
if (!foundTilePoint) {
final int tileY = MyMath.mod(tileAround.y, mapTileUpperBound);
final int tileX = MyMath.mod(tileAround.x, mapTileUpperBound);
final MapTile tileToDownload = new MapTile(zoomLevel, tileX, tileY);
//Drawable currentMapTile = mTileProvider.getMapTile(tile);
boolean ok = loadTile(tileSource, tileToDownload);
if (!ok) {
errors++;
}
tileCounter++;
if (tileCounter % 10 == 0) {
if (isCancelled()) {
return errors;
}
publishProgress(tileCounter, zoomLevel);
}
tilePoints.add(0, tileAround);
}
}
}
prevTile = tile;
}
}
}
} else {
tile = getMapTileFromCoordinates(geoPoint.getLatitude(), geoPoint.getLongitude(), zoomLevel);
prevTile = tile;
//Log.d(Constants.APP_TAG, "New Tile lat " + tile.x + " lon " + tile.y);
int ofsx = tile.x >= 0 ? 0 : -tile.x;
int ofsy = tile.y >= 0 ? 0 : -tile.y;
for (int xAround = tile.x + ofsx; xAround <= tile.x + 1 + ofsx; xAround ++) {
for (int yAround = tile.y + ofsy; yAround <= tile.y + 1 + ofsy; yAround ++) {
Point tileAround = new Point(xAround, yAround);
final int tileY = MyMath.mod(tileAround.y, mapTileUpperBound);
final int tileX = MyMath.mod(tileAround.x, mapTileUpperBound);
final MapTile tileToDownload = new MapTile(zoomLevel, tileX, tileY);
//Drawable currentMapTile = mTileProvider.getMapTile(tile);
boolean ok = loadTile(tileSource, tileToDownload);
if (!ok) {
errors++;
}
tileCounter++;
if (tileCounter % 10 == 0) {
if (isCancelled()) {
return errors;
}
publishProgress(tileCounter, zoomLevel);
}
tilePoints.add(0, tileAround);
}
}
}
prevPoint = geoPoint;
}
}
Log.d(Constants.APP_TAG, "downloaded " + tilePoints.size() + " tiles");
}
return errors;
}
} //DownloadingTask
/**
* Remove all cached tiles in the specified area.
*
* @param ctx
* @param bb
* @param zoomMin
* @param zoomMax
*/
public void cleanAreaAsync(Context ctx, BoundingBoxE6 bb, int zoomMin, int zoomMax) {
new CleaningTask(ctx, bb, zoomMin, zoomMax).execute();
}
/**
* Remove all cached tiles covered by the GeoPoints list.
*
* @param ctx
* @param geoPoints
* @param zoomMin
* @param zoomMax
*/
public void cleanAreaAsync(Context ctx, ArrayList<GeoPoint> geoPoints, int zoomMin, int zoomMax) {
BoundingBoxE6 extendedBounds = extendedBoundsFromGeoPoints(geoPoints, zoomMin);
new CleaningTask(ctx, extendedBounds, zoomMin, zoomMax).execute();
}
/**
*
*/
public BoundingBoxE6 extendedBoundsFromGeoPoints(ArrayList<GeoPoint> geoPoints, int minZoomLevel) {
BoundingBoxE6 bb = BoundingBoxE6.fromGeoPoints(geoPoints);
Point mLowerRight = getMapTileFromCoordinates(bb.getLatSouthE6() * 1E-6, bb.getLonEastE6() * 1E-6, minZoomLevel);
GeoPoint lowerRightPoint = getCoordinatesFromMapTile(mLowerRight.x+1, mLowerRight.y+1, minZoomLevel);
Point mUpperLeft = getMapTileFromCoordinates(bb.getLatNorthE6() * 1E-6, bb.getLonWestE6() * 1E-6, minZoomLevel);
GeoPoint upperLeftPoint = getCoordinatesFromMapTile(mUpperLeft.x-1, mUpperLeft.y-1, minZoomLevel);
BoundingBoxE6 extendedBounds = new BoundingBoxE6(upperLeftPoint.getLatitudeE6(), upperLeftPoint.getLongitudeE6(), lowerRightPoint.getLatitudeE6(), lowerRightPoint.getLongitudeE6());
return extendedBounds;
}
protected class CleaningTask extends CacheManagerTask {
public CleaningTask(Context pCtx, BoundingBoxE6 pBB, final int pZoomMin, final int pZoomMax) {
super(pCtx, pBB, pZoomMin, pZoomMax);
}
@Override
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(mCtx);
mProgressDialog.setTitle("Cleaning tiles");
mProgressDialog.setMessage(zoomMessage(mZoomMin, mZoomMin, mZoomMax));
int total = possibleTilesInArea(mBB, mZoomMin, mZoomMax);
mProgressDialog.setMax(total);
mProgressDialog.show();
}
@Override
protected void onPostExecute(final Integer deleted) {
Toast.makeText(mCtx, "Cleaning completed, " + deleted + " tiles deleted.", Toast.LENGTH_SHORT).show();
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
@Override
protected Integer doInBackground(Object... params) {
int errors = cleanArea();
return errors;
}
/**
* Do the job.
*
* @return the number of tiles deleted.
*/
protected int cleanArea() {
ITileSource tileSource = mTileProvider.getTileSource();
int deleted = 0;
int tileCounter = 0;
for (int zoomLevel = mZoomMin; zoomLevel <= mZoomMax; zoomLevel++) {
Point mLowerRight = getMapTileFromCoordinates(mBB.getLatSouthE6() * 1E-6, mBB.getLonEastE6() * 1E-6, zoomLevel);
Point mUpperLeft = getMapTileFromCoordinates(mBB.getLatNorthE6() * 1E-6, mBB.getLonWestE6() * 1E-6, zoomLevel);
final int mapTileUpperBound = 1 << zoomLevel;
//Get all the MapTiles from the upper left to the lower right:
//In case we used GeoPoint list, we also have to take care of the tiles around the area.
int ofsy = mUpperLeft.y > 0 ? -1 : 0;
int ofsx = mUpperLeft.x > 0 ? -1 : 0;
for (int y = mUpperLeft.y + ofsy; y <= mLowerRight.y + 2 + ofsy; y++) {
for (int x = mUpperLeft.x + ofsx; x <= mLowerRight.x + 2 + ofsx; x++) {
final int tileY = MyMath.mod(y, mapTileUpperBound);
final int tileX = MyMath.mod(x, mapTileUpperBound);
final MapTile tile = new MapTile(zoomLevel, tileX, tileY);
File file = getFileName(tileSource, tile);
if (file.exists()) {
file.delete();
deleted++;
}
tileCounter++;
if (tileCounter % 1000 == 0) {
if (isCancelled()) {
return deleted;
}
publishProgress(tileCounter, zoomLevel);
}
}
}
}
return deleted;
}
} //CleaningTask
/**
* @return volume currently use in the osmdroid local filesystem cache, in bytes.
* Note that this method currently takes a while.
*/
public long currentCacheUsage() {
//return TileWriter.getUsedCacheSpace(); //returned value is not stable! Increase and decrease, for unknown reasons.
return directorySize(OpenStreetMapTileProviderConstants.TILE_PATH_BASE);
}
/**
* @return the capacity of the osmdroid local filesystem cache, in bytes.
* This capacity is currently a hard-coded constant inside osmdroid.
*/
public long cacheCapacity() {
return OpenStreetMapTileProviderConstants.TILE_MAX_CACHE_SIZE_BYTES;
}
/**
* @return the total size of a directory and of its whole content, recursively
*/
public long directorySize(final File pDirectory) {
long usedCacheSpace = 0;
final File[] z = pDirectory.listFiles();
if (z != null) {
for (final File file : z) {
if (file.isFile()) {
usedCacheSpace += file.length();
} else {
if (file.isDirectory()) {
usedCacheSpace += directorySize(file);
}
}
}
}
return usedCacheSpace;
}
}