diff options
Diffstat (limited to 'plugins/aves_map/lib')
| -rw-r--r-- | plugins/aves_map/lib/aves_map.dart | 13 | ||||
| -rw-r--r-- | plugins/aves_map/lib/src/controller.dart | 77 | ||||
| -rw-r--r-- | plugins/aves_map/lib/src/geo_entry.dart | 32 | ||||
| -rw-r--r-- | plugins/aves_map/lib/src/geo_utils.dart | 134 | ||||
| -rw-r--r-- | plugins/aves_map/lib/src/interface.dart | 12 | ||||
| -rw-r--r-- | plugins/aves_map/lib/src/marker/arrow_painter.dart | 44 | ||||
| -rw-r--r-- | plugins/aves_map/lib/src/marker/dot.dart | 18 | ||||
| -rw-r--r-- | plugins/aves_map/lib/src/marker/generator.dart | 138 | ||||
| -rw-r--r-- | plugins/aves_map/lib/src/marker/image.dart | 166 | ||||
| -rw-r--r-- | plugins/aves_map/lib/src/marker/key.dart | 13 | ||||
| -rw-r--r-- | plugins/aves_map/lib/src/overlay/overlay.dart | 17 | ||||
| -rw-r--r-- | plugins/aves_map/lib/src/overlay/tile.dart | 13 | ||||
| -rw-r--r-- | plugins/aves_map/lib/src/style.dart | 134 | ||||
| -rw-r--r-- | plugins/aves_map/lib/src/theme.dart | 33 | ||||
| -rw-r--r-- | plugins/aves_map/lib/src/zoomed_bounds.dart | 105 |
15 files changed, 949 insertions, 0 deletions
diff --git a/plugins/aves_map/lib/aves_map.dart b/plugins/aves_map/lib/aves_map.dart new file mode 100644 index 0000000..2098916 --- /dev/null +++ b/plugins/aves_map/lib/aves_map.dart @@ -0,0 +1,13 @@ +export 'src/controller.dart'; +export 'src/geo_entry.dart'; +export 'src/geo_utils.dart'; +export 'src/interface.dart'; +export 'src/marker/dot.dart'; +export 'src/marker/generator.dart'; +export 'src/marker/image.dart'; +export 'src/marker/key.dart'; +export 'src/overlay/overlay.dart'; +export 'src/overlay/tile.dart'; +export 'src/style.dart'; +export 'src/theme.dart'; +export 'src/zoomed_bounds.dart'; diff --git a/plugins/aves_map/lib/src/controller.dart b/plugins/aves_map/lib/src/controller.dart new file mode 100644 index 0000000..8997993 --- /dev/null +++ b/plugins/aves_map/lib/src/controller.dart @@ -0,0 +1,77 @@ +import 'dart:async'; + +import 'package:aves_map/src/zoomed_bounds.dart'; +import 'package:flutter/foundation.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:leak_tracker/leak_tracker.dart'; + +class AvesMapController { + final StreamController _streamController = StreamController.broadcast(); + ZoomedBounds? _idleBounds; + + ZoomedBounds? get idleBounds => _idleBounds; + + Stream<dynamic> get _events => _streamController.stream; + + Stream<MapControllerMoveEvent> get moveCommands => _events.where((event) => event is MapControllerMoveEvent).cast<MapControllerMoveEvent>(); + + Stream<MapControllerZoomEvent> get zoomCommands => _events.where((event) => event is MapControllerZoomEvent).cast<MapControllerZoomEvent>(); + + Stream<MapControllerRotationResetEvent> get rotationResetCommands => _events.where((event) => event is MapControllerRotationResetEvent).cast<MapControllerRotationResetEvent>(); + + Stream<MapIdleUpdate> get idleUpdates => _events.where((event) => event is MapIdleUpdate).cast<MapIdleUpdate>(); + + Stream<MapMarkerLocationChangeEvent> get markerLocationChanges => _events.where((event) => event is MapMarkerLocationChangeEvent).cast<MapMarkerLocationChangeEvent>(); + + AvesMapController() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$AvesMapController', + object: this, + ); + } + } + + void dispose() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + _streamController.close(); + } + + void moveTo(LatLng latLng) => _streamController.add(MapControllerMoveEvent(latLng)); + + void zoomBy(double delta) => _streamController.add(MapControllerZoomEvent(delta)); + + void resetRotation() => _streamController.add(MapControllerRotationResetEvent()); + + void notifyIdle(ZoomedBounds bounds) { + _idleBounds = bounds; + _streamController.add(MapIdleUpdate(bounds)); + } + + void notifyMarkerLocationChange() => _streamController.add(MapMarkerLocationChangeEvent()); +} + +class MapControllerMoveEvent { + final LatLng latLng; + + MapControllerMoveEvent(this.latLng); +} + +class MapControllerZoomEvent { + final double delta; + + MapControllerZoomEvent(this.delta); +} + +class MapControllerRotationResetEvent {} + +class MapIdleUpdate { + final ZoomedBounds bounds; + + MapIdleUpdate(this.bounds); +} + +class MapMarkerLocationChangeEvent {} diff --git a/plugins/aves_map/lib/src/geo_entry.dart b/plugins/aves_map/lib/src/geo_entry.dart new file mode 100644 index 0000000..4699e38 --- /dev/null +++ b/plugins/aves_map/lib/src/geo_entry.dart @@ -0,0 +1,32 @@ +import 'package:fluster/fluster.dart'; +import 'package:flutter/foundation.dart'; + +class GeoEntry<T> extends Clusterable { + T? entry; + + GeoEntry({ + this.entry, + super.latitude, + super.longitude, + super.isCluster = false, + super.clusterId, + super.pointsSize, + super.markerId, + super.childMarkerId, + }); + + factory GeoEntry.createCluster(BaseCluster cluster, double longitude, double latitude) { + return GeoEntry( + latitude: latitude, + longitude: longitude, + isCluster: cluster.isCluster, + clusterId: cluster.id, + pointsSize: cluster.pointsSize, + markerId: cluster.id.toString(), + childMarkerId: cluster.childMarkerId, + ); + } + + @override + String toString() => '$runtimeType#${shortHash(this)}{isCluster=$isCluster, lat=$latitude, lng=$longitude, clusterId=$clusterId, pointsSize=$pointsSize, markerId=$markerId, childMarkerId=$childMarkerId}'; +} diff --git a/plugins/aves_map/lib/src/geo_utils.dart b/plugins/aves_map/lib/src/geo_utils.dart new file mode 100644 index 0000000..5272482 --- /dev/null +++ b/plugins/aves_map/lib/src/geo_utils.dart @@ -0,0 +1,134 @@ +import 'dart:math'; + +import 'package:latlong2/latlong.dart'; + +class GeoUtils { + static LatLng getLatLngCenter(List<LatLng> points) { + double x = 0; + double y = 0; + double z = 0; + + points.forEach((point) { + final lat = point.latitudeInRad; + final lng = point.longitudeInRad; + x += cos(lat) * cos(lng); + y += cos(lat) * sin(lng); + z += sin(lat); + }); + + final pointCount = points.length; + x /= pointCount; + y /= pointCount; + z /= pointCount; + + final lng = atan2(y, x); + final hyp = sqrt(x * x + y * y); + final lat = atan2(z, hyp); + return LatLng(radianToDeg(lat), radianToDeg(lng)); + } + + static bool contains(LatLng sw, LatLng ne, LatLng? point) { + if (point == null) return false; + final lat = point.latitude; + final lng = point.longitude; + final south = sw.latitude; + final north = ne.latitude; + final west = sw.longitude; + final east = ne.longitude; + return (south <= lat && lat <= north) && (west <= east ? (west <= lng && lng <= east) : (west <= lng || lng <= east)); + } + + // cf https://epsg.io/EPSGCODE.proj4 + // cf https://github.com/stevage/epsg + // cf https://github.com/maRci002/proj4dart/blob/master/test/data/all_proj4_defs.dart + static String? epsgToProj4(int? epsg) { + // `32767` refers to user defined values + if (epsg == null || epsg == 32767) return null; + + if (3038 <= epsg && epsg <= 3051) { + // ETRS89 / UTM (N-E) + final zone = epsg - 3012; + return '+proj=utm +zone=$zone +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs'; + } else if (26700 <= epsg && epsg <= 26799) { + // US State Plane (NAD27): 267xx/320xx + if (26703 <= epsg && epsg <= 26722) { + final zone = epsg - 26700; + return '+proj=utm +zone=$zone +datum=NAD27 +units=m +no_defs'; + } + // NAD27 datum requires loading `nadgrids` for accurate transformation: + // cf https://github.com/proj4js/proj4js/pull/363 + // cf https://github.com/maRci002/proj4dart/issues/8 + if (epsg == 26746) { + // NAD27 / California zone VI + return '+proj=lcc +lat_1=33.88333333333333 +lat_2=32.78333333333333 +lat_0=32.16666666666666 +lon_0=-116.25 +x_0=609601.2192024384 +y_0=0 +datum=NAD27 +units=us-ft +no_defs'; + } else if (epsg == 26771) { + // NAD27 / Illinois East + return '+proj=tmerc +lat_0=36.66666666666666 +lon_0=-88.33333333333333 +k=0.9999749999999999 +x_0=152400.3048006096 +y_0=0 +datum=NAD27 +units=us-ft +no_defs'; + } + } else if ((26900 <= epsg && epsg <= 26999) || (32100 <= epsg && epsg <= 32199)) { + // US State Plane (NAD83): 269xx/321xx + if (epsg == 26966) { + // NAD83 Georgia East + return '+proj=tmerc +lat_0=30 +lon_0=-82.16666666666667 +k=0.9999 +x_0=200000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs'; + } + } else if (32200 <= epsg && epsg <= 32299) { + // WGS72 / UTM northern hemisphere: 322zz where zz is UTM zone number + final zone = epsg - 32200; + return '+proj=utm +zone=$zone +ellps=WGS72 +towgs84=0,0,4.5,0,0,0.554,0.2263 +units=m +no_defs'; + } else if (32300 <= epsg && epsg <= 32399) { + // WGS72 / UTM southern hemisphere: 323zz where zz is UTM zone number + final zone = epsg - 32300; + return '+proj=utm +zone=$zone +south +ellps=WGS72 +towgs84=0,0,4.5,0,0,0.554,0.2263 +units=m +no_defs'; + } else if (32400 <= epsg && epsg <= 32460) { + // WGS72BE / UTM northern hemisphere: 324zz where zz is UTM zone number + final zone = epsg - 32400; + return '+proj=utm +zone=$zone +ellps=WGS72 +towgs84=0,0,1.9,0,0,0.814,-0.38 +units=m +no_defs'; + } else if (32500 <= epsg && epsg <= 32599) { + // WGS72BE / UTM southern hemisphere: 325zz where zz is UTM zone number + final zone = epsg - 32500; + return '+proj=utm +zone=$zone +south +ellps=WGS72 +towgs84=0,0,1.9,0,0,0.814,-0.38 +units=m +no_defs'; + } else if (32600 <= epsg && epsg <= 32699) { + // WGS84 / UTM northern hemisphere: 326zz where zz is UTM zone number + final zone = epsg - 32600; + return '+proj=utm +zone=$zone +datum=WGS84 +units=m +no_defs'; + } else if (32700 <= epsg && epsg <= 32799) { + // WGS84 / UTM southern hemisphere: 327zz where zz is UTM zone number + final zone = epsg - 32700; + return '+proj=utm +zone=$zone +south +datum=WGS84 +units=m +no_defs'; + } + + return null; + } +} + +// cf https://www.maptiler.com/google-maps-coordinates-tile-bounds-projection/ +class MapServiceHelper { + final int tileSize; + late final double initialResolution, originShift; + + MapServiceHelper(this.tileSize) { + initialResolution = 2 * pi * 6378137 / tileSize; + originShift = 2 * pi * 6378137 / 2.0; + } + + int matrixSize(int zoomLevel) { + return 1 << zoomLevel; + } + + Point<double> pixelsToMeters(double px, double py, int zoomLevel) { + double res = resolution(zoomLevel); + double mx = px * res - originShift; + double my = -py * res + originShift; + return Point(mx, my); + } + + double resolution(int zoomLevel) { + return initialResolution / matrixSize(zoomLevel); + } + + Point<double> tileTopLeft(int tx, int ty, int zoomLevel) { + final px = tx * tileSize; + final py = ty * tileSize; + return pixelsToMeters(px.toDouble(), py.toDouble(), zoomLevel); + } +} diff --git a/plugins/aves_map/lib/src/interface.dart b/plugins/aves_map/lib/src/interface.dart new file mode 100644 index 0000000..3f2cc17 --- /dev/null +++ b/plugins/aves_map/lib/src/interface.dart @@ -0,0 +1,12 @@ +import 'package:aves_map/src/geo_entry.dart'; +import 'package:aves_map/src/marker/key.dart'; +import 'package:flutter/material.dart'; +import 'package:latlong2/latlong.dart'; + +typedef MarkerClusterBuilder<T> = Map<MarkerKey<T>, GeoEntry<T>> Function(); +typedef MarkerWidgetBuilder<T> = Widget Function(MarkerKey<T> key); +typedef MarkerImageReadyChecker<T> = bool Function(MarkerKey<T> key); +typedef UserZoomChangeCallback = void Function(double zoom); +typedef MapTapCallback = void Function(LatLng location); +typedef MarkerTapCallback<T> = void Function(GeoEntry<T> geoEntry); +typedef MarkerLongPressCallback<T> = void Function(GeoEntry<T> geoEntry, LatLng tapLocation); diff --git a/plugins/aves_map/lib/src/marker/arrow_painter.dart b/plugins/aves_map/lib/src/marker/arrow_painter.dart new file mode 100644 index 0000000..c38367f --- /dev/null +++ b/plugins/aves_map/lib/src/marker/arrow_painter.dart @@ -0,0 +1,44 @@ +import 'package:flutter/material.dart'; + +class MarkerArrowPainter extends CustomPainter { + final Color color, outlineColor; + final double outlineWidth; + final Size size; + + const MarkerArrowPainter({ + required this.color, + required this.outlineColor, + required this.outlineWidth, + required this.size, + }); + + @override + void paint(Canvas canvas, Size size) { + final triangleWidth = this.size.width; + final triangleHeight = this.size.height; + + final bottomCenter = Offset(size.width / 2, size.height); + final topLeft = bottomCenter + Offset(-triangleWidth / 2, -triangleHeight); + final topRight = bottomCenter + Offset(triangleWidth / 2, -triangleHeight); + + canvas.drawPath( + Path() + ..moveTo(bottomCenter.dx, bottomCenter.dy) + ..lineTo(topRight.dx, topRight.dy) + ..lineTo(topLeft.dx, topLeft.dy) + ..close(), + Paint()..color = outlineColor); + + canvas.translate(0, -outlineWidth.ceilToDouble()); + canvas.drawPath( + Path() + ..moveTo(bottomCenter.dx, bottomCenter.dy) + ..lineTo(topRight.dx, topRight.dy) + ..lineTo(topLeft.dx, topLeft.dy) + ..close(), + Paint()..color = color); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +} diff --git a/plugins/aves_map/lib/src/marker/dot.dart b/plugins/aves_map/lib/src/marker/dot.dart new file mode 100644 index 0000000..b43b81b --- /dev/null +++ b/plugins/aves_map/lib/src/marker/dot.dart @@ -0,0 +1,18 @@ +import 'package:aves_map/src/theme.dart'; +import 'package:aves_ui/aves_ui.dart'; +import 'package:flutter/material.dart'; + +class DotMarker extends StatelessWidget { + const DotMarker({super.key}); + + @override + Widget build(BuildContext context) { + return const AvesDot( + diameter: MapThemeData.markerDotDiameter, + outerBorderWidth: MapThemeData.markerOuterBorderWidth, + innerBorderWidth: MapThemeData.markerInnerBorderWidth, + getOuterBorderColor: MapThemeData.markerThemedOuterBorderColor, + getInnerBorderColor: MapThemeData.markerThemedInnerBorderColor, + ); + } +} diff --git a/plugins/aves_map/lib/src/marker/generator.dart b/plugins/aves_map/lib/src/marker/generator.dart new file mode 100644 index 0000000..ca536b3 --- /dev/null +++ b/plugins/aves_map/lib/src/marker/generator.dart @@ -0,0 +1,138 @@ +import 'dart:ui' as ui; + +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +// generate bitmap from widget, for Google map +class MarkerGeneratorWidget<T extends Key> extends StatefulWidget { + final List<Widget> markers; + final bool Function(T markerKey) isReadyToRender; + final void Function(T markerKey, Uint8List bitmap) onRendered; + + const MarkerGeneratorWidget({ + super.key, + required this.markers, + required this.isReadyToRender, + required this.onRendered, + }); + + @override + State<MarkerGeneratorWidget<T>> createState() => _MarkerGeneratorWidgetState<T>(); +} + +class _MarkerGeneratorWidgetState<T extends Key> extends State<MarkerGeneratorWidget<T>> { + final Set<_MarkerGeneratorItem<T>> _items = {}; + + @override + void initState() { + super.initState(); + _checkNextFrame(); + } + + @override + void didUpdateWidget(covariant MarkerGeneratorWidget<T> oldWidget) { + super.didUpdateWidget(oldWidget); + final devicePixelRatio = View.of(context).devicePixelRatio; + widget.markers.forEach((markerWidget) { + final item = _getOrCreate( + markerKey: markerWidget.key as T, + devicePixelRatio: devicePixelRatio, + ); + item.globalKey = GlobalKey(); + }); + _checkNextFrame(); + } + + void _checkNextFrame() { + WidgetsBinding.instance.addPostFrameCallback((_) async { + if (!mounted) return; + final waitingItems = _items.where((v) => v.isWaiting).toSet(); + final readyItems = waitingItems.where((v) => widget.isReadyToRender(v.markerKey)).toSet(); + readyItems.forEach((v) async { + final bitmap = await v.render(); + if (bitmap != null) { + widget.onRendered(v.markerKey, bitmap); + } + }); + if (readyItems.length < waitingItems.length) { + _checkNextFrame(); + setState(() {}); + } + }); + } + + @override + Widget build(BuildContext context) { + return Transform.translate( + offset: Offset(MediaQuery.sizeOf(context).width, 0), + child: Material( + type: MaterialType.transparency, + child: Stack( + children: _items.map((item) { + return RepaintBoundary( + key: item.globalKey, + child: widget.markers.firstWhereOrNull((v) => v.key == item.markerKey) ?? const SizedBox(), + ); + }).toList(), + ), + ), + ); + } + + _MarkerGeneratorItem _getOrCreate({ + required T markerKey, + required double devicePixelRatio, + }) { + final existingItem = _items.firstWhereOrNull((v) => v.markerKey == markerKey); + if (existingItem != null) return existingItem; + + final newItem = _MarkerGeneratorItem( + markerKey: markerKey, + devicePixelRatio: devicePixelRatio, + ); + _items.add(newItem); + return newItem; + } +} + +enum MarkerGeneratorItemState { waiting, rendering, done } + +class _MarkerGeneratorItem<T extends Key> { + final T markerKey; + final double devicePixelRatio; + GlobalKey? globalKey; + MarkerGeneratorItemState state = MarkerGeneratorItemState.waiting; + + _MarkerGeneratorItem({ + required this.markerKey, + required this.devicePixelRatio, + }); + + bool get isWaiting => state == MarkerGeneratorItemState.waiting; + + Future<Uint8List?> render() async { + Uint8List? bytes; + final _globalKey = globalKey; + if (_globalKey != null) { + state = MarkerGeneratorItemState.rendering; + final boundary = _globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary; + if (boundary.hasSize && boundary.size != Size.zero) { + try { + final image = await boundary.toImage(pixelRatio: devicePixelRatio); + final byteData = await image.toByteData(format: ui.ImageByteFormat.png); + bytes = byteData?.buffer.asUint8List(); + } catch (error) { + // happens when widget is offscreen + debugPrint('failed to render image for key=$_globalKey with error=$error'); + } + } + state = bytes != null ? MarkerGeneratorItemState.done : MarkerGeneratorItemState.waiting; + } + return bytes; + } + + @override + String toString() => '$runtimeType#${shortHash(this)}{markerKey=$markerKey, globalKey=$globalKey, state=$state}'; +} diff --git a/plugins/aves_map/lib/src/marker/image.dart b/plugins/aves_map/lib/src/marker/image.dart new file mode 100644 index 0000000..58f0377 --- /dev/null +++ b/plugins/aves_map/lib/src/marker/image.dart @@ -0,0 +1,166 @@ +import 'package:aves_map/aves_map.dart'; +import 'package:aves_map/src/marker/arrow_painter.dart'; +import 'package:collection/collection.dart'; +import 'package:custom_rounded_rectangle_border/custom_rounded_rectangle_border.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:intl/intl.dart' as intl; +import 'package:latlong2/latlong.dart'; + +class ImageMarker extends StatelessWidget { + final int? count; + final intl.NumberFormat countFormatter; + final bool drawArrow; + final Widget Function(double extent) buildThumbnailImage; + + static const double outerBorderRadiusDim = 8; + static const outerBorderWidth = MapThemeData.markerOuterBorderWidth; + static const innerBorderWidth = MapThemeData.markerInnerBorderWidth; + static const extent = MapThemeData.markerImageExtent; + static const arrowSize = MapThemeData.markerArrowSize; + static const outerBorderRadius = BorderRadius.all(Radius.circular(outerBorderRadiusDim)); + static const innerRadius = Radius.circular(outerBorderRadiusDim - outerBorderWidth); + static const innerBorderRadius = BorderRadius.all(innerRadius); + + ImageMarker({ + super.key, + required this.count, + required String? locale, + this.drawArrow = true, + required this.buildThumbnailImage, + }) : countFormatter = intl.NumberFormat.decimalPattern(locale); + + @override + Widget build(BuildContext context) { + Widget child = buildThumbnailImage(extent); + + // need to be sized for the Google map marker generator + child = SizedBox( + width: extent, + height: extent, + child: child, + ); + + final theme = Theme.of(context); + final isDark = theme.brightness == Brightness.dark; + final outerBorderColor = MapThemeData.markerThemedOuterBorderColor(isDark); + final innerBorderColor = MapThemeData.markerThemedInnerBorderColor(isDark); + + final outerDecoration = BoxDecoration( + border: Border.fromBorderSide(BorderSide( + color: outerBorderColor, + width: outerBorderWidth, + )), + borderRadius: outerBorderRadius, + ); + + final innerDecoration = BoxDecoration( + border: Border.fromBorderSide(BorderSide( + color: innerBorderColor, + width: innerBorderWidth, + )), + borderRadius: innerBorderRadius, + ); + + child = DecoratedBox( + decoration: innerDecoration, + position: DecorationPosition.foreground, + child: ClipRRect( + borderRadius: innerBorderRadius, + child: child, + ), + ); + + if (count != null) { + final borderSide = BorderSide( + color: innerBorderColor, + width: innerBorderWidth, + ); + child = Stack( + children: [ + child, + Container( + padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 2), + decoration: ShapeDecoration( + color: theme.colorScheme.primary, + shape: _buildCornerDetailShape(context, borderSide), + ), + child: Text( + countFormatter.format(count), + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.onPrimary, + ), + ), + ), + ], + ); + } + + child = Container( + decoration: outerDecoration, + child: child, + ); + + if (drawArrow) { + child = CustomPaint( + foregroundPainter: MarkerArrowPainter( + color: innerBorderColor, + outlineColor: outerBorderColor, + outlineWidth: outerBorderWidth, + size: arrowSize, + ), + child: Padding( + padding: EdgeInsets.only(bottom: arrowSize.height), + child: child, + ), + ); + } + + return child; + } + + ShapeBorder _buildCornerDetailShape(BuildContext context, BorderSide side) { + final isRtl = Directionality.of(context) == TextDirection.rtl; + return CustomRoundedRectangleBorder( + leftSide: side, + rightSide: side, + topSide: side, + bottomSide: side, + topLeftCornerSide: isRtl ? null : side, + topRightCornerSide: isRtl ? side : null, + bottomLeftCornerSide: isRtl ? side : null, + bottomRightCornerSide: isRtl ? null : side, + borderRadius: BorderRadius.only( + topLeft: isRtl ? Radius.zero : innerRadius, + topRight: isRtl ? innerRadius : Radius.zero, + bottomLeft: isRtl ? innerRadius : Radius.zero, + bottomRight: isRtl ? Radius.zero : innerRadius, + ), + ); + } + + static const _crs = Epsg3857(); + + static GeoEntry<T>? markerMatch<T>(LatLng position, double zoom, Set<GeoEntry<T>> markers) { + final pressOffset = _crs.latLngToOffset(position, zoom); + + const double markerWidth = extent; + const double markerHeight = extent; + + return markers.firstWhereOrNull((marker) { + final latitude = marker.latitude; + final longitude = marker.longitude; + if (latitude == null || longitude == null) return false; + + final markerAnchorPoint = _crs.latLngToOffset(LatLng(latitude, longitude), zoom); + final bottom = markerAnchorPoint.dy; + final top = bottom - markerHeight; + final left = markerAnchorPoint.dx - markerWidth / 2; + final right = left + markerWidth; + final markerRect = Rect.fromLTRB(left, top, right, bottom); + + return markerRect.contains(pressOffset); + }); + } +} diff --git a/plugins/aves_map/lib/src/marker/key.dart b/plugins/aves_map/lib/src/marker/key.dart new file mode 100644 index 0000000..188ec01 --- /dev/null +++ b/plugins/aves_map/lib/src/marker/key.dart @@ -0,0 +1,13 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter/material.dart'; + +@immutable +class MarkerKey<T> extends LocalKey with EquatableMixin { + final T entry; + final int? count; + + @override + List<Object?> get props => [entry, count]; + + const MarkerKey(this.entry, this.count); +} diff --git a/plugins/aves_map/lib/src/overlay/overlay.dart b/plugins/aves_map/lib/src/overlay/overlay.dart new file mode 100644 index 0000000..6fafa66 --- /dev/null +++ b/plugins/aves_map/lib/src/overlay/overlay.dart @@ -0,0 +1,17 @@ +import 'package:aves_map/src/overlay/tile.dart'; +import 'package:flutter/painting.dart'; +import 'package:latlong2/latlong.dart'; + +mixin MapOverlay { + String get id; + + bool get canOverlay; + + LatLng? get topLeft; + + LatLng? get bottomRight; + + ImageProvider get imageProvider; + + Future<MapTile?> getTile(int tx, int ty, int? zoomLevel); +} diff --git a/plugins/aves_map/lib/src/overlay/tile.dart b/plugins/aves_map/lib/src/overlay/tile.dart new file mode 100644 index 0000000..cc5e5a0 --- /dev/null +++ b/plugins/aves_map/lib/src/overlay/tile.dart @@ -0,0 +1,13 @@ +import 'package:flutter/foundation.dart'; + +@immutable +class MapTile { + final int width, height; + final Uint8List data; + + const MapTile({ + required this.width, + required this.height, + required this.data, + }); +} diff --git a/plugins/aves_map/lib/src/style.dart b/plugins/aves_map/lib/src/style.dart new file mode 100644 index 0000000..b0d0066 --- /dev/null +++ b/plugins/aves_map/lib/src/style.dart @@ -0,0 +1,134 @@ +import 'dart:convert'; + +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; + +// OSM raster tile providers: https://wiki.openstreetmap.org/wiki/Raster_tile_providers +// OSM vector tile providers: https://wiki.openstreetmap.org/wiki/Vector_tiles#Providers +// Leaflet providers preview: https://leaflet-extras.github.io/leaflet-providers/preview/ +// OpenMapTiles styles: https://openmaptiles.org/styles/ +// Examples: https://github.com/deckerst/aves/wiki/Custom-maps +class EntryMapStyle extends Equatable { + final String key; + final String? name; + final bool isRaster; + final String? url; // not strictly a `Uri` as it may contain templates like `{x}` + final List<String> subdomains; + final String? userAgent; + final bool needMobileService; + final bool isHeavy; + + @override + List<Object?> get props => [key, name, isRaster, url]; + + const EntryMapStyle({ + required this.key, + this.name, + this.isRaster = true, + this.url, + List<String>? subdomains, + this.userAgent, + this.needMobileService = false, + this.isHeavy = false, + }) : subdomains = subdomains ?? const ['a', 'b', 'c']; + + static EntryMapStyle? fromJson(String? jsonString) { + if (jsonString == null || jsonString.isEmpty) return null; + + try { + final jsonMap = jsonDecode(jsonString); + if (jsonMap is Map<String, dynamic>) { + return _fromMap(jsonMap); + } + debugPrint('failed to parse style from json=$jsonString'); + } catch (error) { + // no need for stack + debugPrint('failed to parse style from json=$jsonString error=$error'); + } + return null; + } + + String toJson() => jsonEncode(_toMap()); + + static EntryMapStyle _fromMap(Map<String, dynamic> jsonMap) { + return EntryMapStyle( + key: jsonMap['key'], + name: jsonMap['name'], + isRaster: jsonMap['isRaster'], + url: jsonMap['url'], + subdomains: (jsonMap['subdomains'] as List<dynamic>?)?.cast<String>(), + userAgent: jsonMap['userAgent'], + needMobileService: jsonMap['needMobileService'], + isHeavy: jsonMap['isHeavy'], + ); + } + + Map<String, dynamic> _toMap() { + return { + 'key': key, + 'name': name, + 'isRaster': isRaster, + 'url': url, + 'subdomains': subdomains, + 'userAgent': userAgent, + 'needMobileService': needMobileService, + 'isHeavy': isHeavy, + }; + } +} + +class EntryMapStyles { + // Google + + static const googleNormal = EntryMapStyle( + key: 'googleNormal', + needMobileService: true, + isHeavy: true, + ); + + static const googleHybrid = EntryMapStyle( + key: 'googleHybrid', + needMobileService: true, + isHeavy: true, + ); + + static const googleTerrain = EntryMapStyle( + key: 'googleTerrain', + needMobileService: true, + isHeavy: true, + ); + + // Vector (OpenMapTiles) + + static const osmLiberty = EntryMapStyle( + key: 'osmLiberty', + isRaster: false, + ); + + // Raster (Leaflet) + + static const openTopoMap = EntryMapStyle( + key: 'openTopoMap', + url: 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', + ); + + static const osmHot = EntryMapStyle( + key: 'osmHot', + url: 'https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', + ); + + static const stamenWatercolor = EntryMapStyle( + key: 'stamenWatercolor', + url: 'https://watercolormaps.collection.cooperhewitt.org/tile/watercolor/{z}/{x}/{y}.jpg', + ); + + // default styles that do not need mobile services + static List<EntryMapStyle> baseStyles = [ + // Vector (OpenMapTiles) + osmLiberty, + // Raster (Leaflet) + openTopoMap, + osmHot, + stamenWatercolor, + ]; +} diff --git a/plugins/aves_map/lib/src/theme.dart b/plugins/aves_map/lib/src/theme.dart new file mode 100644 index 0000000..521d94d --- /dev/null +++ b/plugins/aves_map/lib/src/theme.dart @@ -0,0 +1,33 @@ +import 'package:flutter/material.dart'; + +enum MapNavigationButton { back, close, map, none } + +class MapThemeData { + final bool interactive, showCoordinateFilter; + final MapNavigationButton navigationButton; + final Animation<double> scale; + final VisualDensity visualDensity; + final double? mapHeight; + final EdgeInsets attributionPadding; + + const MapThemeData({ + required this.interactive, + required this.showCoordinateFilter, + required this.navigationButton, + required this.scale, + required this.visualDensity, + required this.mapHeight, + required this.attributionPadding, + }); + + static const double markerOuterBorderWidth = 1.5; + static const double markerInnerBorderWidth = 2; + static const double markerImageExtent = 48.0; + static const Size markerArrowSize = Size(8, 6); + static const double markerDotDiameter = 16; + static const int trackWidth = 5; + + static Color markerThemedOuterBorderColor(bool isDark) => isDark ? Colors.white30 : Colors.black26; + + static Color markerThemedInnerBorderColor(bool isDark) => isDark ? const Color(0xFF212121) : Colors.white; +} diff --git a/plugins/aves_map/lib/src/zoomed_bounds.dart b/plugins/aves_map/lib/src/zoomed_bounds.dart new file mode 100644 index 0000000..3c709bd --- /dev/null +++ b/plugins/aves_map/lib/src/zoomed_bounds.dart @@ -0,0 +1,105 @@ +import 'dart:math'; +import 'dart:ui'; + +import 'package:aves_map/src/geo_utils.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:latlong2/latlong.dart'; + +@immutable +class ZoomedBounds extends Equatable { + final LatLng sw, ne; + final double zoom, rotation; + + // returns [southwestLng, southwestLat, northeastLng, northeastLat], as expected by Fluster + List<double> get boundingBox => [sw.longitude, sw.latitude, ne.longitude, ne.latitude]; + + // Map services (Google Maps, OpenStreetMap) use the spherical Mercator projection (EPSG 3857). + static const _crs = Epsg3857(); + + // The projected center appears visually in the middle of the bounds. + LatLng get projectedCenter { + final swPoint = _crs.latLngToOffset(sw, zoom); + final nePoint = _crs.latLngToOffset(ne, zoom); + // assume no padding around bounds + return _crs.offsetToLatLng((swPoint + nePoint) / 2, zoom); + } + + @override + List<Object?> get props => [sw, ne, zoom, rotation]; + + const ZoomedBounds({ + required this.sw, + required this.ne, + required this.zoom, + required this.rotation, + }); + + static const _collocationMaxDeltaThreshold = 360 / (2 << 19); + + factory ZoomedBounds.fromPoints({ + required Set<LatLng> points, + double collocationZoom = 20, + }) { + var west = .0, south = .0, east = .0, north = .0; + var zoom = collocationZoom; + + if (points.isNotEmpty) { + final first = points.first; + west = first.longitude; + south = first.latitude; + east = first.longitude; + north = first.latitude; + + for (var point in points) { + final lng = point.longitude; + final lat = point.latitude; + if (lng < west) west = lng; + if (lat < south) south = lat; + if (lng > east) east = lng; + if (lat > north) north = lat; + } + + final boundsDelta = max(north - south, east - west); + if (boundsDelta > _collocationMaxDeltaThreshold) { + zoom = max(1, log(360) / ln2 - log(boundsDelta) / ln2); + } + } + return ZoomedBounds( + sw: LatLng(south, west), + ne: LatLng(north, east), + zoom: zoom, + rotation: 0, + ); + } + + ZoomedBounds copyWith({ + LatLng? sw, + LatLng? ne, + double? zoom, + double? rotation, + }) { + return ZoomedBounds( + sw: sw ?? this.sw, + ne: ne ?? this.ne, + zoom: zoom ?? this.zoom, + rotation: rotation ?? this.rotation, + ); + } + + bool contains(LatLng location) => GeoUtils.contains(sw, ne, location); + + Size toDisplaySize() { + final swPoint = _crs.latLngToOffset(sw, zoom); + final nePoint = _crs.latLngToOffset(ne, zoom); + return Size((swPoint.dx - nePoint.dx).abs(), (swPoint.dy - nePoint.dy).abs()); + } + + Offset offset(LatLng location) { + final swPoint = _crs.latLngToOffset(sw, zoom); + final nePoint = _crs.latLngToOffset(ne, zoom); + final point = _crs.latLngToOffset(location, zoom); + return Offset(point.dx - swPoint.dx, point.dy - nePoint.dy); + } +} |
