forked from fleaflet/flutter_map
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtile_layer.dart
684 lines (598 loc) · 24.4 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
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/src/core/bounds.dart';
import 'package:flutter_map/src/core/point.dart';
import 'package:flutter_map/src/core/util.dart' as util;
import 'package:flutter_map/src/geo/crs/crs.dart';
import 'package:flutter_map/src/geo/latlng_bounds.dart';
import 'package:flutter_map/src/gestures/map_events.dart';
import 'package:flutter_map/src/layer/tile_layer/tile.dart';
import 'package:flutter_map/src/layer/tile_layer/tile_bounds/tile_bounds.dart';
import 'package:flutter_map/src/layer/tile_layer/tile_bounds/tile_bounds_at_zoom.dart';
import 'package:flutter_map/src/layer/tile_layer/tile_builder.dart';
import 'package:flutter_map/src/layer/tile_layer/tile_coordinates.dart';
import 'package:flutter_map/src/layer/tile_layer/tile_display.dart';
import 'package:flutter_map/src/layer/tile_layer/tile_image.dart';
import 'package:flutter_map/src/layer/tile_layer/tile_image_manager.dart';
import 'package:flutter_map/src/layer/tile_layer/tile_provider/base_tile_provider.dart';
import 'package:flutter_map/src/layer/tile_layer/tile_provider/tile_provider_io.dart'
if (dart.library.html) 'package:flutter_map/src/layer/tile_layer/tile_provider/tile_provider_web.dart';
import 'package:flutter_map/src/layer/tile_layer/tile_range.dart';
import 'package:flutter_map/src/layer/tile_layer/tile_range_calculator.dart';
import 'package:flutter_map/src/layer/tile_layer/tile_scale_calculator.dart';
import 'package:flutter_map/src/layer/tile_layer/tile_update_event.dart';
import 'package:flutter_map/src/layer/tile_layer/tile_update_transformer.dart';
import 'package:flutter_map/src/map/flutter_map_state.dart';
part 'tile_layer_options.dart';
/// Describes the needed properties to create a tile-based layer. A tile is an
/// image bound to a specific geographical position.
///
/// You should read up about the options by exploring each one, or visiting
/// https://docs.fleaflet.dev/usage/layers/tile-layer. Some are important to
/// avoid issues.
class TileLayer extends StatefulWidget {
/// 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;
/// Follows the same structure as [urlTemplate]. If specified, this URL is
/// used only if an error occurs when loading the [urlTemplate].
final String? fallbackUrl;
/// 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 int? 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 int? 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;
// Control how tiles are displayed and whether they are faded in when loaded.
// Defaults to TileDisplay.fadeIn().
final TileDisplay tileDisplay;
/// Color shown behind the tiles
final Color backgroundColor;
/// Provider with which to load map tiles
///
/// The default is [NetworkNoRetryTileProvider]. Alternatively, use
/// [NetworkTileProvider] for a network provider which will retry requests.
///
/// Both network providers will use some form of caching, although not reliable. For
/// better options, see https://docs.fleaflet.dev/usage/layers/tile-layer#caching.
///
/// `userAgentPackageName` is a construction parameter, which should be passed
/// the application's correct package name, such as 'com.example.app'. If no
/// value is passed, it defaults to 'unknown'. This parameter is used to form
/// part of the 'User-Agent' header, which is important to avoid blocking by
/// tile servers. Namely, the header is the following 'flutter_map (<packageName>)'.
///
/// Header rules are as follows, after 'User-Agent' is generated as above:
///
/// * If no provider is specified here, the default will be used with
/// 'User-Agent' header injected (recommended)
/// * If a provider is specified here with no 'User-Agent' header, that
/// provider will be used and the 'User-Agent' header will be injected
/// * If a provider is specified here with a 'User-Agent' header, that
/// provider will be used and the 'User-Agent' header will not be changed to any created here
///
/// [AssetTileProvider] and [FileTileProvider] are alternatives to network
/// providers, which use the [urlTemplate] as a path instead.
/// For example, 'assets/map/{z}/{x}/{y}.png' or
/// '/storage/emulated/0/map_app/tiles/{z}/{x}/{y}.png'.
///
/// Custom [TileProvider]s can also be used, but these will not follow the header
/// rules above.
final TileProvider tileProvider;
/// When panning the map, keep this many rows and columns of tiles before
/// unloading them.
final int keepBuffer;
/// When panning the map, extend the tilerange by this many tiles in each
/// direction.
/// Will cause extra tile loads, and impact performance.
/// Be careful increasing this beyond 0 or 1.
final int panBuffer;
/// 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;
/// 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 executed if an error occurs 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;
// 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;
/// Stream to notify the [TileLayer] that it needs resetting
final Stream<void>? reset;
/// Only load tiles that are within these bounds
final LatLngBounds? tileBounds;
/// This transformer modifies how/when tile updates and pruning are triggered
/// based on [MapEvent]s. It is a StreamTransformer and therefore it is
/// possible to filter/modify/throttle the [TileUpdateEvent]s. Defaults to
/// [TileUpdateTransformers.ignoreTapEvents] which disables loading/pruning
/// for map taps, secondary taps and long presses. See TileUpdateTransformers
/// for more transformer presets or implement your own.
///
/// Note: Changing the [tileUpdateTransformer] after TileLayer is created has
/// no affect.
final TileUpdateTransformer tileUpdateTransformer;
TileLayer({
super.key,
this.urlTemplate,
this.fallbackUrl,
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.panBuffer = 0,
this.backgroundColor = const Color(0xFFE0E0E0),
this.errorImage,
TileProvider? tileProvider,
this.tms = false,
this.wmsOptions,
this.tileDisplay = const TileDisplay.fadeIn(),
this.retinaMode = false,
this.errorTileCallback,
this.templateFunction = util.template,
this.tileBuilder,
this.evictErrorTileStrategy = EvictErrorTileStrategy.none,
this.reset,
this.tileBounds,
TileUpdateTransformer? tileUpdateTransformer,
String userAgentPackageName = 'unknown',
}) : assert(
tileDisplay.map(
instantaneous: (_) => true,
fadeIn: (fadeIn) => fadeIn.duration > Duration.zero)!,
),
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,
additionalOptions = additionalOptions == null
? const <String, String>{}
: Map.from(additionalOptions),
tileProvider = tileProvider == null
? NetworkNoRetryTileProvider(
headers: {'User-Agent': 'flutter_map ($userAgentPackageName)'},
)
: (tileProvider
..headers = <String, String>{
...tileProvider.headers,
if (!tileProvider.headers.containsKey('User-Agent'))
'User-Agent': 'flutter_map ($userAgentPackageName)',
}),
tileUpdateTransformer =
tileUpdateTransformer ?? TileUpdateTransformers.ignoreTapEvents;
@override
State<StatefulWidget> createState() => _TileLayerState();
}
class _TileLayerState extends State<TileLayer> with TickerProviderStateMixin {
bool _initializedFromMapState = false;
final TileImageManager _tileImageManager = TileImageManager();
late TileBounds _tileBounds;
late TileRangeCalculator _tileRangeCalculator;
late TileScaleCalculator _tileScaleCalculator;
// We have to hold on to the mapController hashCode to determine whether we
// need to reinitialize the listeners. didChangeDependencies is called on
// every map movement and if we unsubscribe and resubscribe every time we
// miss events.
int? _mapControllerHashCode;
// Only one of these two subscriptions will be initialized. If
// TileLayer.tileUpdateTransformer is null then we subscribe to map movement
// otherwise we subscribe to tile update events which are transformed from
// map movements.
StreamSubscription<TileUpdateEvent>? _tileUpdateSubscription;
StreamSubscription<void>? _resetSub;
Timer? _pruneLater;
@override
void initState() {
super.initState();
if (widget.reset != null) {
_resetSub = widget.reset?.listen(
(_) => _tileImageManager.removeAll(
widget.evictErrorTileStrategy,
),
);
}
_tileRangeCalculator = TileRangeCalculator(tileSize: widget.tileSize);
}
// This is called on every map movement so we should avoid expensive logic
// where possible.
@override
void didChangeDependencies() {
super.didChangeDependencies();
final mapState = FlutterMapState.maybeOf(context)!;
final mapController = mapState.mapController;
if (_mapControllerHashCode != mapController.hashCode) {
_tileUpdateSubscription?.cancel();
_mapControllerHashCode = mapController.hashCode;
_tileUpdateSubscription = mapController.mapEventStream
.map((mapEvent) => TileUpdateEvent(mapEvent: mapEvent))
.transform(widget.tileUpdateTransformer)
.listen((event) => _onTileUpdateEvent(mapState, event));
}
bool reloadTiles = false;
if (!_initializedFromMapState ||
_tileBounds.shouldReplace(
mapState.options.crs, widget.tileSize, widget.tileBounds)) {
reloadTiles = true;
_tileBounds = TileBounds(
crs: mapState.options.crs,
tileSize: widget.tileSize,
latLngBounds: widget.tileBounds,
);
}
if (!_initializedFromMapState ||
_tileScaleCalculator.shouldReplace(
mapState.options.crs, widget.tileSize)) {
reloadTiles = true;
_tileScaleCalculator = TileScaleCalculator(
crs: mapState.options.crs,
tileSize: widget.tileSize,
);
}
if (reloadTiles) {
_tryWaitForSizeToBeInitialized(
mapState,
() => _loadAndPruneInVisibleBounds(mapState),
);
}
_initializedFromMapState = true;
}
@override
void didUpdateWidget(TileLayer oldWidget) {
super.didUpdateWidget(oldWidget);
bool reloadTiles = false;
// There is no caching in TileRangeCalculator so we can just replace it.
_tileRangeCalculator = TileRangeCalculator(tileSize: widget.tileSize);
if (_tileBounds.shouldReplace(
_tileBounds.crs, widget.tileSize, widget.tileBounds)) {
_tileBounds = TileBounds(
crs: _tileBounds.crs,
tileSize: widget.tileSize,
latLngBounds: widget.tileBounds,
);
reloadTiles = true;
}
if (_tileScaleCalculator.shouldReplace(
_tileScaleCalculator.crs, widget.tileSize)) {
_tileScaleCalculator = TileScaleCalculator(
crs: _tileScaleCalculator.crs,
tileSize: widget.tileSize,
);
}
if (oldWidget.retinaMode != widget.retinaMode) {
reloadTiles = true;
}
if (oldWidget.minZoom != widget.minZoom ||
oldWidget.maxZoom != widget.maxZoom) {
reloadTiles |=
!_tileImageManager.allWithinZoom(widget.minZoom, widget.maxZoom);
}
if (!reloadTiles) {
final oldUrl =
oldWidget.wmsOptions?._encodedBaseUrl ?? oldWidget.urlTemplate;
final newUrl = widget.wmsOptions?._encodedBaseUrl ?? widget.urlTemplate;
final oldOptions = oldWidget.additionalOptions;
final newOptions = widget.additionalOptions;
if (oldUrl != newUrl ||
!(const MapEquality<String, String>())
.equals(oldOptions, newOptions)) {
_tileImageManager.reloadImages(widget, _tileBounds);
}
}
if (reloadTiles) {
_tileImageManager.removeAll(widget.evictErrorTileStrategy);
_loadAndPruneInVisibleBounds(FlutterMapState.maybeOf(context)!);
} else if (oldWidget.tileDisplay != widget.tileDisplay) {
_tileImageManager.updateTileDisplay(widget.tileDisplay);
}
}
@override
void dispose() {
_tileUpdateSubscription?.cancel();
_tileImageManager.removeAll(widget.evictErrorTileStrategy);
_resetSub?.cancel();
_pruneLater?.cancel();
widget.tileProvider.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final map = FlutterMapState.maybeOf(context)!;
if (_outsideZoomLimits(map.zoom.round())) return const SizedBox.shrink();
final tileZoom = _clampToNativeZoom(map.zoom);
final tileBoundsAtZoom = _tileBounds.atZoom(tileZoom);
final visibleTileRange = _tileRangeCalculator.calculate(
mapState: map,
tileZoom: tileZoom,
);
// For a given map event both this rebuild method and the tile
// loading/pruning logic will be fired. Any TileImages which are not
// rendered in a corresponding Tile after this build will not become
// visible until the next build. Therefore, in case this build is executed
// before the loading/updating, we must pre-create the missing TileImages
// and add them to the widget tree so that when they are loaded they notify
// the Tile and become visible.
_tileImageManager.createMissingTiles(
visibleTileRange,
tileBoundsAtZoom,
createTileImage: (coordinate) => _createTileImage(
coordinate,
tileBoundsAtZoom,
),
);
final currentPixelOrigin = CustomPoint<double>(
map.pixelOrigin.x.toDouble(),
map.pixelOrigin.y.toDouble(),
);
_tileScaleCalculator.clearCacheUnlessZoomMatches(map.zoom);
return Container(
color: widget.backgroundColor,
child: Stack(
children: [
..._tileImageManager
.inRenderOrder(widget.maxZoom, tileZoom)
.map((tileImage) {
return Tile(
// Must be an ObjectKey, not a ValueKey using the coordinates, in
// case we remove and replace the TileImage with a different one.
key: ObjectKey(tileImage),
scaledTileSize: _tileScaleCalculator.scaledTileSize(
map.zoom,
tileImage.coordinates.z,
),
currentPixelOrigin: currentPixelOrigin,
tileImage: tileImage,
tileBuilder: widget.tileBuilder,
);
}),
],
),
);
}
TileImage _createTileImage(
TileCoordinates coordinates,
TileBoundsAtZoom tileBoundsAtZoom,
) {
return TileImage(
vsync: this,
coordinates: coordinates,
imageProvider: widget.tileProvider.getImage(
tileBoundsAtZoom.wrap(coordinates),
widget,
),
onLoadError: _onTileLoadError,
onLoadComplete: _onTileLoadComplete,
tileDisplay: widget.tileDisplay,
errorImage: widget.errorImage,
);
}
// Load and/or prune tiles according to the visible bounds of the [event]
// center/zoom, or the current center/zoom if not specified.
void _onTileUpdateEvent(FlutterMapState mapState, TileUpdateEvent event) {
final zoom = event.loadZoomOverride ?? mapState.zoom;
final center = event.loadCenterOverride ?? mapState.center;
final tileZoom = _clampToNativeZoom(zoom);
final visibleTileRange = _tileRangeCalculator.calculate(
mapState: mapState,
tileZoom: tileZoom,
center: center,
viewingZoom: zoom,
);
if (event.load) {
if (!_outsideZoomLimits(tileZoom)) _loadTiles(visibleTileRange);
}
if (event.prune) {
_tileImageManager.evictErrorTiles(
visibleTileRange, widget.evictErrorTileStrategy);
_tileImageManager.prune(widget.evictErrorTileStrategy);
}
}
// Load new tiles in the visible bounds and prune those outside.
void _loadAndPruneInVisibleBounds(FlutterMapState mapState) {
final tileZoom = _clampToNativeZoom(mapState.zoom);
final visibleTileRange = _tileRangeCalculator.calculate(
mapState: mapState,
tileZoom: tileZoom,
);
if (!_outsideZoomLimits(tileZoom)) _loadTiles(visibleTileRange);
_tileImageManager.evictErrorTiles(
visibleTileRange, widget.evictErrorTileStrategy);
_tileImageManager.prune(widget.evictErrorTileStrategy);
}
// For all valid TileCoordinates in the [tileLoadRange], expanded by the
// [TileLayer.panBuffer], this method will do the following depending on
// whether a matching TileImage already exists or not:
// * Exists: Mark it as current and initiate image loading if it has not
// already been initiated.
// * Does not exist: Creates the TileImage (they are current when created)
// and initiates loading.
//
// Additionally, any current TileImages outside of the [tileLoadRange],
// expanded by the [TileLayer.panBuffer] + [TileLayer.keepBuffer], are marked
// as not current.
void _loadTiles(DiscreteTileRange tileLoadRange) {
final tileZoom = tileLoadRange.zoom;
tileLoadRange = tileLoadRange.expand(widget.panBuffer);
// Mark tiles outside of the tile load range as no longer current.
_tileImageManager.markAsNoLongerCurrentOutside(
tileZoom,
tileLoadRange.expand(widget.keepBuffer),
);
// Build the queue of tiles to load. Marks all tiles with valid coordinates
// in the tileLoadRange as current.
final tileBoundsAtZoom = _tileBounds.atZoom(tileZoom);
final tilesToLoad = _tileImageManager.setCurrentAndReturnNotLoadedTiles(
tileBoundsAtZoom.validCoordinatesIn(tileLoadRange),
createTile: (coordinates) =>
_createTileImage(coordinates, tileBoundsAtZoom));
// Re-order the tiles by their distance to the center of the range.
final tileCenter = tileLoadRange.center;
tilesToLoad.sort(
(a, b) => a.coordinates
.distanceTo(tileCenter)
.compareTo(b.coordinates.distanceTo(tileCenter)),
);
// Create the new Tiles.
for (final tile in tilesToLoad) {
tile.load();
}
}
// Rounds the zoom to the nearest int and clamps it to the native zoom limits
// if there are any.
int _clampToNativeZoom(double zoom) {
int result = zoom.round();
if (widget.minNativeZoom != null) {
result = math.max(result, widget.minNativeZoom!);
}
if (widget.maxNativeZoom != null) {
result = math.min(result, widget.maxNativeZoom!);
}
return result;
}
void _onTileLoadError(TileImage tile, Object error, StackTrace? stackTrace) {
debugPrint(error.toString());
widget.errorTileCallback?.call(tile, error, stackTrace);
}
// This is called whether the tile loads successfully or with an error.
void _onTileLoadComplete(TileCoordinates coordinates) {
if (!_tileImageManager.containsTileAt(coordinates) ||
!_tileImageManager.allLoaded) {
return;
}
widget.tileDisplay.map(instantaneous: (_) {
_tileImageManager.prune(widget.evictErrorTileStrategy);
}, fadeIn: (fadeIn) {
// Wait a bit more than tileFadeInDuration to trigger a pruning so that
// we don't see tile removal under a fading tile.
_pruneLater?.cancel();
_pruneLater = Timer(
fadeIn.duration + const Duration(milliseconds: 50),
() => _tileImageManager.prune(widget.evictErrorTileStrategy),
);
});
}
bool _outsideZoomLimits(num zoom) =>
zoom < widget.minZoom || zoom > widget.maxZoom;
// A workaround for the fact that FlutterMapState size initialization has a
// race condition where sometimes the size is set to CustomPoint(0,0) before
// it is set to the correct value. When this occurs, code that relies on the
// visible bounds will not work correctly. Sometimes it requires more than
// one postFrameCallback to get a non zero size.
void _tryWaitForSizeToBeInitialized(
FlutterMapState mapState,
VoidCallback callback, {
int retries = 3,
}) {
if (retries >= 0 && mapState.size == const CustomPoint(0, 0)) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_tryWaitForSizeToBeInitialized(
mapState,
callback,
retries: retries - 1,
);
});
} else {
callback();
}
}
}