-
-
Notifications
You must be signed in to change notification settings - Fork 860
/
tile_layer.dart
1480 lines (1241 loc) · 41.5 KB
/
tile_layer.dart
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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dart:async';
import 'dart:math' as math;
import 'package:collection/collection.dart' show MapEquality;
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_map/src/core/bounds.dart';
import 'package:flutter_map/src/core/util.dart' as util;
import 'package:flutter_map/src/map/map.dart';
import 'package:latlong2/latlong.dart';
import 'package:tuple/tuple.dart';
typedef TemplateFunction = String Function(
String str, Map<String, String> data);
enum EvictErrorTileStrategy {
// never evict error Tiles
none,
// evict error Tiles during _pruneTiles / _abortLoading calls
dispose,
// evict error Tiles which are not visible anymore but respect margin (see keepBuffer option)
// (Tile's zoom level not equals current _tileZoom or Tile is out of viewport)
notVisibleRespectMargin,
// evict error Tiles which are not visible anymore
// (Tile's zoom level not equals current _tileZoom or Tile is out of viewport)
notVisible,
}
typedef ErrorTileCallBack = void Function(Tile tile, dynamic error);
/// Describes the needed properties to create a tile-based layer. A tile is an
/// image bound to a specific geographical position.
class TileLayerOptions extends LayerOptions {
/// Defines the structure to create the URLs for the tiles. `{s}` means one of
/// the available subdomains (can be omitted) `{z}` zoom level `{x}` and `{y}`
/// — tile coordinates `{r}` can be used to add "@2x" to the URL to
/// load retina tiles (can be omitted)
///
/// Example:
///
/// https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png
///
/// Is translated to this:
///
/// https://a.tile.openstreetmap.org/12/2177/1259.png
final String? urlTemplate;
/// If `true`, inverses Y axis numbering for tiles (turn this on for
/// [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
final bool tms;
/// If not `null`, then tiles will pull's WMS protocol requests
final WMSTileLayerOptions? wmsOptions;
/// Size for the tile.
/// Default is 256
final double tileSize;
// The minimum zoom level down to which this layer will be
// displayed (inclusive).
final double minZoom;
/// The maximum zoom level up to which this layer will be displayed
/// (inclusive). In most tile providers goes from 0 to 19.
final double maxZoom;
/// Minimum zoom number the tile source has available. If it is specified, the
/// tiles on all zoom levels lower than minNativeZoom will be loaded from
/// minNativeZoom level and auto-scaled.
final double? minNativeZoom;
/// Maximum zoom number the tile source has available. If it is specified, the
/// tiles on all zoom levels higher than maxNativeZoom will be loaded from
/// maxNativeZoom level and auto-scaled.
final double? maxNativeZoom;
/// If set to true, the zoom number used in tile URLs will be reversed
/// (`maxZoom - zoom` instead of `zoom`)
final bool zoomReverse;
/// The zoom number used in tile URLs will be offset with this value.
final double zoomOffset;
/// List of subdomains for the URL.
///
/// Example:
///
/// Subdomains = {a,b,c}
///
/// and the URL is as follows:
///
/// https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png
///
/// then:
///
/// https://a.tile.openstreetmap.org/{z}/{x}/{y}.png
/// https://b.tile.openstreetmap.org/{z}/{x}/{y}.png
/// https://c.tile.openstreetmap.org/{z}/{x}/{y}.png
final List<String> subdomains;
/// Color shown behind the tiles.
final Color backgroundColor;
/// Opacity of the rendered tile
final double opacity;
/// Provider to load the tiles. The default is `NonCachingNetworkTileProvider()` which
/// doesn't cache tiles and won't retry the HTTP request. Use `NetworkTileProvider()` for
/// a provider which will retry requests. For the best caching implementations, see the
/// flutter_map readme.
///
/// In order to use images from the asset folder set this option to
/// AssetTileProvider() Note that it requires the urlTemplate to target
/// assets, for example:
///
/// ```dart
/// urlTemplate: "assets/map/anholt_osmbright/{z}/{x}/{y}.png",
/// ```
///
/// In order to use images from the filesystem set this option to
/// FileTileProvider() Note that it requires the urlTemplate to target the
/// file system, for example:
///
/// ```dart
/// urlTemplate: "/storage/emulated/0/tiles/some_place/{z}/{x}/{y}.png",
/// ```
///
/// Furthermore you create your custom implementation by subclassing
/// TileProvider
///
final TileProvider tileProvider;
/// When panning the map, keep this many rows and columns of tiles before
/// unloading them.
final int keepBuffer;
/// Placeholder to show until tile images are fetched by the provider.
final ImageProvider? placeholderImage;
/// Tile image to show in place of the tile that failed to load.
final ImageProvider? errorImage;
/// Static information that should replace placeholders in the [urlTemplate].
/// Applying API keys is a good example on how to use this parameter.
///
/// Example:
///
/// ```dart
///
/// TileLayerOptions(
/// urlTemplate: "https://api.tiles.mapbox.com/v4/"
/// "{id}/{z}/{x}/{y}{r}.png?access_token={accessToken}",
/// additionalOptions: {
/// 'accessToken': '<PUT_ACCESS_TOKEN_HERE>',
/// 'id': 'mapbox.streets',
/// },
/// ),
/// ```
///
final Map<String, String> additionalOptions;
/// Tiles will not update more than once every `updateInterval` (default 200
/// milliseconds) when panning. It can be null (but it will calculating for
/// loading tiles every frame when panning / zooming, flutter is fast) This
/// can save some fps and even bandwidth (ie. when fast panning / animating
/// between long distances in short time)
final Duration? updateInterval;
/// Tiles fade in duration in milliseconds (default 100). This can be null to
/// avoid fade in.
final Duration? tileFadeInDuration;
/// Opacity start value when Tile starts fade in (0.0 - 1.0) Takes effect if
/// `tileFadeInDuration` is not null
final double tileFadeInStart;
/// Opacity start value when an exists Tile starts fade in with different Url
/// (0.0 - 1.0) Takes effect when `tileFadeInDuration` is not null and if
/// `overrideTilesWhenUrlChanges` if true
final double tileFadeInStartWhenOverride;
/// `false`: current Tiles will be first dropped and then reload via new url
/// (default) `true`: current Tiles will be visible until new ones aren't
/// loaded (new Tiles are loaded independently) @see
/// https://github.com/johnpryan/flutter_map/issues/583
final bool overrideTilesWhenUrlChanges;
/// If `true`, it will request four tiles of half the specified size and a
/// bigger zoom level in place of one to utilize the high resolution.
///
/// If `true` then MapOptions's `maxZoom` should be `maxZoom - 1` since
/// retinaMode just simulates retina display by playing with `zoomOffset`. If
/// geoserver supports retina `@2` tiles then it it advised to use them
/// instead of simulating it (use {r} in the [urlTemplate])
///
/// It is advised to use retinaMode if display supports it, write code like
/// this:
///
/// ```dart
/// TileLayerOptions(
/// retinaMode: true && MediaQuery.of(context).devicePixelRatio > 1.0,
/// ),
/// ```
final bool retinaMode;
/// This callback will be execute if some errors occur when fetching tiles.
final ErrorTileCallBack? errorTileCallback;
final TemplateFunction templateFunction;
/// Function which may Wrap Tile with custom Widget
/// There are predefined examples in 'tile_builder.dart'
final TileBuilder? tileBuilder;
/// Function which may wrap Tiles Container with custom Widget
/// There are predefined examples in 'tile_builder.dart'
final TilesContainerBuilder? tilesContainerBuilder;
// If a Tile was loaded with error and if strategy isn't `none` then TileProvider
// will be asked to evict Image based on current strategy
// (see #576 - even Error Images are cached in flutter)
final EvictErrorTileStrategy evictErrorTileStrategy;
/// This option is useful when you have a transparent layer: rather than
/// keeping the old layer visible when zooming (resulting in both layers
/// being temporarily visible), the old layer is removed as quickly as
/// possible when this is set to `true` (default `false`).
///
/// This option is likely to cause some flickering of the transparent layer,
/// most noticeable when using pinch-to-zoom. It's best used with maps that
/// have `interactive` set to `false`, and zoom using buttons that call
/// `MapController.move()`.
///
/// When set to `true`, the `tileFadeIn*` options will be ignored.
final bool fastReplace;
///Attribution widget builder
final WidgetBuilder? attributionBuilder;
///aligment of the attribution text on the map widget
final Alignment attributionAlignment;
/// Stream to notify the [TileLayer] that it needs resetting
Stream<void>? reset;
/// Only load tiles that are within these bounds
LatLngBounds? tileBounds;
TileLayerOptions(
{this.attributionAlignment = Alignment.bottomRight,
this.attributionBuilder,
Key? key,
// TODO: make required
this.urlTemplate,
double tileSize = 256.0,
double minZoom = 0.0,
double maxZoom = 18.0,
this.minNativeZoom,
this.maxNativeZoom,
this.zoomReverse = false,
double zoomOffset = 0.0,
Map<String, String>? additionalOptions,
this.subdomains = const <String>[],
this.keepBuffer = 2,
this.backgroundColor = const Color(0xFFE0E0E0),
this.placeholderImage,
this.errorImage,
this.tileProvider = const NonCachingNetworkTileProvider(),
this.tms = false,
// ignore: avoid_init_to_null
this.wmsOptions = null,
this.opacity = 1.0,
// Tiles will not update more than once every `updateInterval` milliseconds
// (default 200) when panning. It can be 0 (but it will calculating for
// loading tiles every frame when panning / zooming, flutter is fast) This
// can save some fps and even bandwidth (ie. when fast panning / animating
// between long distances in short time)
// TODO: change to Duration
int updateInterval = 200,
// Tiles fade in duration in milliseconds (default 100). This can be set to
// 0 to avoid fade in
// TODO: change to Duration
int tileFadeInDuration = 100,
this.tileFadeInStart = 0.0,
this.tileFadeInStartWhenOverride = 0.0,
this.overrideTilesWhenUrlChanges = false,
this.retinaMode = false,
this.errorTileCallback,
Stream<void>? rebuild,
this.templateFunction = util.template,
this.tileBuilder,
this.tilesContainerBuilder,
this.evictErrorTileStrategy = EvictErrorTileStrategy.none,
this.fastReplace = false,
this.reset,
this.tileBounds})
: updateInterval =
updateInterval <= 0 ? null : Duration(milliseconds: updateInterval),
tileFadeInDuration = tileFadeInDuration <= 0
? null
: Duration(milliseconds: tileFadeInDuration),
assert(tileFadeInStart >= 0.0 && tileFadeInStart <= 1.0),
assert(tileFadeInStartWhenOverride >= 0.0 &&
tileFadeInStartWhenOverride <= 1.0),
maxZoom =
wmsOptions == null && retinaMode && maxZoom > 0.0 && !zoomReverse
? maxZoom - 1.0
: maxZoom,
minZoom =
wmsOptions == null && retinaMode && maxZoom > 0.0 && zoomReverse
? math.max(minZoom + 1.0, 0)
: minZoom,
zoomOffset = wmsOptions == null && retinaMode && maxZoom > 0.0
? (zoomReverse ? zoomOffset - 1.0 : zoomOffset + 1.0)
: zoomOffset,
tileSize = wmsOptions == null && retinaMode && maxZoom > 0.0
? (tileSize / 2.0).floorToDouble()
: tileSize,
// copy additionalOptions Map if not null, so we can safely compare old
// and new Map inside didUpdateWidget with MapEquality.
additionalOptions = additionalOptions == null
? const <String, String>{}
: Map.from(additionalOptions),
super(key: key, rebuild: rebuild);
}
class WMSTileLayerOptions {
final service = 'WMS';
final request = 'GetMap';
/// url of WMS service.
/// Ex.: 'http://ows.mundialis.de/services/service?'
final String baseUrl;
/// list of WMS layers to show
final List<String> layers;
/// list of WMS styles
final List<String> styles;
/// WMS image format (use 'image/png' for layers with transparency)
final String format;
/// Version of the WMS service to use
final String version;
/// tile transparency flag
final bool transparent;
/// Encode boolean values as uppercase in request
final bool uppercaseBoolValue;
// TODO find a way to implicit pass of current map [Crs]
final Crs crs;
/// other request parameters
final Map<String, String> otherParameters;
late final String _encodedBaseUrl;
late final double _versionNumber;
WMSTileLayerOptions({
required this.baseUrl,
this.layers = const [],
this.styles = const [],
this.format = 'image/png',
this.version = '1.1.1',
this.transparent = true,
this.uppercaseBoolValue = false,
this.crs = const Epsg3857(),
this.otherParameters = const {},
}) {
_versionNumber = double.tryParse(version.split('.').take(2).join('.')) ?? 0;
_encodedBaseUrl = _buildEncodedBaseUrl();
}
String _buildEncodedBaseUrl() {
final projectionKey = _versionNumber >= 1.3 ? 'crs' : 'srs';
final buffer = StringBuffer(baseUrl)
..write('&service=$service')
..write('&request=$request')
..write('&layers=${layers.map(Uri.encodeComponent).join(',')}')
..write('&styles=${styles.map(Uri.encodeComponent).join(',')}')
..write('&format=${Uri.encodeComponent(format)}')
..write('&$projectionKey=${Uri.encodeComponent(crs.code)}')
..write('&version=${Uri.encodeComponent(version)}')
..write(
'&transparent=${uppercaseBoolValue ? transparent.toString().toUpperCase() : transparent}');
otherParameters
.forEach((k, v) => buffer.write('&$k=${Uri.encodeComponent(v)}'));
return buffer.toString();
}
String getUrl(Coords coords, int tileSize, bool retinaMode) {
final tileSizePoint = CustomPoint(tileSize, tileSize);
final nvPoint = coords.scaleBy(tileSizePoint);
final sePoint = nvPoint + tileSizePoint;
final nvCoords = crs.pointToLatLng(nvPoint, coords.z as double)!;
final seCoords = crs.pointToLatLng(sePoint, coords.z as double)!;
final nv = crs.projection.project(nvCoords);
final se = crs.projection.project(seCoords);
final bounds = Bounds(nv, se);
final bbox = (_versionNumber >= 1.3 && crs is Epsg4326)
? [bounds.min.y, bounds.min.x, bounds.max.y, bounds.max.x]
: [bounds.min.x, bounds.min.y, bounds.max.x, bounds.max.y];
final buffer = StringBuffer(_encodedBaseUrl);
buffer.write('&width=${retinaMode ? tileSize * 2 : tileSize}');
buffer.write('&height=${retinaMode ? tileSize * 2 : tileSize}');
buffer.write('&bbox=${bbox.join(',')}');
return buffer.toString();
}
}
class TileLayerWidget extends StatelessWidget {
final TileLayerOptions options;
const TileLayerWidget({Key? key, required this.options}) : super(key: key);
@override
Widget build(BuildContext context) {
final mapState = MapState.maybeOf(context)!;
return TileLayer(
mapState: mapState,
stream: mapState.onMoved,
options: options,
);
}
}
class TileLayer extends StatefulWidget {
final TileLayerOptions options;
final MapState mapState;
final Stream<void> stream;
TileLayer({
required this.options,
required this.mapState,
required this.stream,
}) : super(key: options.key);
@override
State<StatefulWidget> createState() {
return _TileLayerState();
}
}
class _TileLayerState extends State<TileLayer> with TickerProviderStateMixin {
MapState get map => widget.mapState;
TileLayerOptions get options => widget.options;
late Bounds _globalTileRange;
Tuple2<double, double>? _wrapX;
Tuple2<double, double>? _wrapY;
double? _tileZoom;
//ignore: unused_field
Level? _level;
StreamSubscription? _moveSub;
StreamSubscription? _resetSub;
StreamController<LatLng?>? _throttleUpdate;
late CustomPoint _tileSize;
final Map<String, Tile> _tiles = {};
final Map<double, Level> _levels = {};
Timer? _pruneLater;
@override
void initState() {
super.initState();
_tileSize = CustomPoint(options.tileSize, options.tileSize);
_resetView();
_update(null);
_moveSub = widget.stream.listen((_) => _handleMove());
if (options.reset != null) {
_resetSub = options.reset?.listen((_) => _resetTiles());
}
_initThrottleUpdate();
}
@override
void didUpdateWidget(TileLayer oldWidget) {
super.didUpdateWidget(oldWidget);
var reloadTiles = false;
if (oldWidget.options.tileSize != options.tileSize) {
_tileSize = CustomPoint(options.tileSize, options.tileSize);
reloadTiles = true;
}
if (oldWidget.options.retinaMode != options.retinaMode) {
reloadTiles = true;
}
reloadTiles |= _isZoomOutsideMinMax();
if (oldWidget.options.updateInterval != options.updateInterval) {
_throttleUpdate?.close();
_initThrottleUpdate();
}
if (!reloadTiles) {
final oldUrl = oldWidget.options.wmsOptions?._encodedBaseUrl ??
oldWidget.options.urlTemplate;
final newUrl = options.wmsOptions?._encodedBaseUrl ?? options.urlTemplate;
final oldOptions = oldWidget.options.additionalOptions;
final newOptions = options.additionalOptions;
if (oldUrl != newUrl ||
!(const MapEquality<String, String>())
.equals(oldOptions, newOptions)) {
if (options.overrideTilesWhenUrlChanges) {
for (final tile in _tiles.values) {
tile.imageProvider = options.tileProvider
.getImage(_wrapCoords(tile.coords), options);
tile.loadTileImage();
}
} else {
reloadTiles = true;
}
}
}
if (reloadTiles) {
_removeAllTiles();
_resetView();
_update(null);
}
}
bool _isZoomOutsideMinMax() {
for (final tile in _tiles.values) {
if (tile.level.zoom > (options.maxZoom) ||
tile.level.zoom < (options.minZoom)) {
return true;
}
}
return false;
}
void _initThrottleUpdate() {
if (options.updateInterval == null) {
_throttleUpdate = null;
} else {
_throttleUpdate = StreamController<LatLng?>(sync: true);
_throttleUpdate!.stream
.transform(
util.throttleStreamTransformerWithTrailingCall<LatLng?>(
options.updateInterval!,
),
)
.listen(_update);
}
}
@override
void dispose() {
_removeAllTiles();
_resetSub?.cancel();
_moveSub?.cancel();
_pruneLater?.cancel();
options.tileProvider.dispose();
_throttleUpdate?.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
final tilesToRender = _tiles.values.toList()..sort();
final tileWidgets = <Widget>[
for (var tile in tilesToRender) _createTileWidget(tile)
];
final tilesContainer = Stack(
children: tileWidgets,
);
final tilesLayer = options.tilesContainerBuilder == null
? tilesContainer
: options.tilesContainerBuilder!(
context,
tilesContainer,
tilesToRender,
);
final attributionLayer = widget.options.attributionBuilder?.call(context);
return Opacity(
opacity: options.opacity,
child: Container(
color: options.backgroundColor,
child: Stack(
alignment: widget.options.attributionAlignment,
children: [
tilesLayer,
if (attributionLayer != null) attributionLayer,
],
),
),
);
}
Widget _createTileWidget(Tile tile) {
final tilePos = tile.tilePos;
final level = tile.level;
final tileSize = getTileSize();
final pos = (tilePos).multiplyBy(level.scale) + level.translatePoint;
final num width = tileSize.x * level.scale;
final num height = tileSize.y * level.scale;
final Widget content = AnimatedTile(
tile: tile,
errorImage: options.errorImage,
tileBuilder: options.tileBuilder,
);
return Positioned(
key: ValueKey(tile.coordsKey),
left: pos.x.toDouble(),
top: pos.y.toDouble(),
width: width.toDouble(),
height: height.toDouble(),
child: content,
);
}
void _abortLoading() {
final toRemove = <String>[];
for (final entry in _tiles.entries) {
final tile = entry.value;
if (tile.coords.z != _tileZoom) {
if (tile.loaded == null) {
toRemove.add(entry.key);
}
}
}
for (final key in toRemove) {
final tile = _tiles[key]!;
tile.tileReady = null;
tile.dispose(tile.loadError &&
options.evictErrorTileStrategy != EvictErrorTileStrategy.none);
_tiles.remove(key);
}
}
CustomPoint getTileSize() {
return _tileSize;
}
bool _hasLevelChildren(double lvl) {
for (final tile in _tiles.values) {
if (tile.coords.z == lvl) {
return true;
}
}
return false;
}
Level? _updateLevels() {
final zoom = _tileZoom;
final maxZoom = options.maxZoom;
if (zoom == null) return null;
final toRemove = <double>[];
for (final entry in _levels.entries) {
final z = entry.key;
final lvl = entry.value;
if (z == zoom || _hasLevelChildren(z)) {
lvl.zIndex = maxZoom - (zoom - z).abs();
} else {
toRemove.add(z);
}
}
for (final z in toRemove) {
_removeTilesAtZoom(z);
_levels.remove(z);
}
var level = _levels[zoom];
final map = this.map;
if (level == null) {
level = _levels[zoom] = Level();
level.zIndex = maxZoom;
level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom);
level.zoom = zoom;
_setZoomTransform(level, map.center, map.zoom);
}
return _level = level;
}
void _pruneTiles() {
final zoom = _tileZoom;
if (zoom == null) {
_removeAllTiles();
return;
}
for (final entry in _tiles.entries) {
final tile = entry.value;
tile.retain = tile.current;
}
for (final entry in _tiles.entries) {
final tile = entry.value;
if (tile.current && !tile.active) {
final coords = tile.coords;
if (!_retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
_retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
}
}
}
final toRemove = <String>[];
for (final entry in _tiles.entries) {
final tile = entry.value;
if (!tile.retain) {
toRemove.add(entry.key);
}
}
for (final key in toRemove) {
_removeTile(key);
}
}
void _removeTilesAtZoom(double zoom) {
final toRemove = <String>[];
for (final entry in _tiles.entries) {
if (entry.value.coords.z != zoom) {
continue;
}
toRemove.add(entry.key);
}
for (final key in toRemove) {
_removeTile(key);
}
}
///removes all loaded tiles and resets the view
void _resetTiles() {
_removeAllTiles();
_resetView();
}
void _removeAllTiles() {
final toRemove = Map<String, Tile>.from(_tiles);
for (final key in toRemove.keys) {
_removeTile(key);
}
}
bool _retainParent(double x, double y, double z, double minZoom) {
final x2 = (x / 2).floorToDouble();
final y2 = (y / 2).floorToDouble();
final z2 = z - 1;
final coords2 = Coords(x2, y2);
coords2.z = z2;
final key = _tileCoordsToKey(coords2);
final tile = _tiles[key];
if (tile != null) {
if (tile.active) {
tile.retain = true;
return true;
} else if (tile.loaded != null) {
tile.retain = true;
}
}
if (z2 > minZoom) {
return _retainParent(x2, y2, z2, minZoom);
}
return false;
}
void _retainChildren(double x, double y, double z, double maxZoom) {
for (var i = 2 * x; i < 2 * x + 2; i++) {
for (var j = 2 * y; j < 2 * y + 2; j++) {
final coords = Coords(i, j);
coords.z = z + 1;
final key = _tileCoordsToKey(coords);
final tile = _tiles[key];
if (tile != null) {
if (tile.active) {
tile.retain = true;
continue;
} else if (tile.loaded != null) {
tile.retain = true;
}
}
if (z + 1 < maxZoom) {
_retainChildren(i, j, z + 1, maxZoom);
}
}
}
}
void _resetView() {
_setView(map.center, map.zoom);
}
double _clampZoom(double zoom) {
if (null != options.minNativeZoom && zoom < options.minNativeZoom!) {
return options.minNativeZoom!;
}
if (null != options.maxNativeZoom && options.maxNativeZoom! < zoom) {
return options.maxNativeZoom!;
}
return zoom;
}
void _setView(LatLng center, double zoom) {
double? tileZoom = _clampZoom(zoom.roundToDouble());
if ((tileZoom > options.maxZoom) || (tileZoom < options.minZoom)) {
tileZoom = null;
}
_tileZoom = tileZoom;
_abortLoading();
_updateLevels();
_resetGrid();
if (_tileZoom != null) {
_update(center);
}
_pruneTiles();
}
void _setZoomTransforms(LatLng center, double zoom) {
for (final i in _levels.keys) {
_setZoomTransform(_levels[i]!, center, zoom);
}
}
void _setZoomTransform(Level level, LatLng center, double zoom) {
final scale = map.getZoomScale(zoom, level.zoom);
final pixelOrigin = map.getNewPixelOrigin(center, zoom).round();
if (level.origin == null) {
return;
}
final translate = level.origin!.multiplyBy(scale) - pixelOrigin;
level.translatePoint = translate;
level.scale = scale;
}
void _resetGrid() {
final map = this.map;
final crs = map.options.crs;
final tileSize = getTileSize();
final tileZoom = _tileZoom;
final bounds = map.getPixelWorldBounds(_tileZoom);
if (bounds != null) {
_globalTileRange = _pxBoundsToTileRange(bounds);
}
// wrapping
_wrapX = crs.wrapLng;
if (_wrapX != null) {
final first =
(map.project(LatLng(0, crs.wrapLng!.item1), tileZoom).x / tileSize.x)
.floorToDouble();
final second =
(map.project(LatLng(0, crs.wrapLng!.item2), tileZoom).x / tileSize.y)
.ceilToDouble();
_wrapX = Tuple2(first, second);
}
_wrapY = crs.wrapLat;
if (_wrapY != null) {
final first =
(map.project(LatLng(crs.wrapLat!.item1, 0), tileZoom).y / tileSize.x)
.floorToDouble();
final second =
(map.project(LatLng(crs.wrapLat!.item2, 0), tileZoom).y / tileSize.y)
.ceilToDouble();
_wrapY = Tuple2(first, second);
}
}
void _handleMove() {
final tileZoom = _clampZoom(map.zoom.roundToDouble());
if (_tileZoom == null) {
// if there is no _tileZoom available it means we are out within zoom level
// we will restore fully via _setView call if we are back on trail
if ((tileZoom <= options.maxZoom) && (tileZoom >= options.minZoom)) {
_tileZoom = tileZoom;
setState(() {
_setView(map.center, tileZoom);
_setZoomTransforms(map.center, map.zoom);
});
}
} else {
setState(() {
if ((tileZoom - _tileZoom!).abs() >= 1) {
// It was a zoom lvl change
_setView(map.center, tileZoom);
_setZoomTransforms(map.center, map.zoom);
} else {
if (_throttleUpdate == null) {
_update(null);
} else {
_throttleUpdate!.add(null);
}
_setZoomTransforms(map.center, map.zoom);
}
});
}
}
Bounds _getTiledPixelBounds(LatLng center) {
final scale = map.getZoomScale(map.zoom, _tileZoom);
final pixelCenter = map.project(center, _tileZoom).floor();
final halfSize = map.size / (scale * 2);
return Bounds(pixelCenter - halfSize, pixelCenter + halfSize);
}
// Private method to load tiles in the grid's active zoom level according to
// map bounds
void _update(LatLng? center) {
if (_tileZoom == null) {
return;
}
final zoom = _clampZoom(map.zoom);
center ??= map.center;
final pixelBounds = _getTiledPixelBounds(center);
final tileRange = _pxBoundsToTileRange(pixelBounds);
final tileCenter = tileRange.center;
final queue = <Coords<num>>[];
final margin = options.keepBuffer;
final noPruneRange = Bounds(
tileRange.bottomLeft - CustomPoint(margin, -margin),
tileRange.topRight + CustomPoint(margin, -margin),
);
for (final entry in _tiles.entries) {
final tile = entry.value;
final c = tile.coords;
if (tile.current == true &&
(c.z != _tileZoom || !noPruneRange.contains(CustomPoint(c.x, c.y)))) {
tile.current = false;
}
}
// _update just loads more tiles. If the tile zoom level differs too much
// from the map's, let _setView reset levels and prune old tiles.
if ((zoom - _tileZoom!).abs() > 1) {
_setView(center, zoom);
return;
}
// create a queue of coordinates to load tiles from
for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
final coords = Coords(i.toDouble(), j.toDouble());
coords.z = _tileZoom!;
if (options.tileBounds != null) {
final tilePxBounds = _pxBoundsToTileRange(