如何用flutter_map的CrsSimple实现无地理位置的大图片瓦片查看器
flutter_map 实现大图瓦片浏览方案
完全可以通过flutter_map内置的CrsSimple坐标系复现你在Leaflet中的实现效果,以下是对应你的参数的完整实现代码:
前置依赖
先在pubspec.yaml中引入依赖:
dependencies: flutter_map: ^6.1.0 latlong2: ^0.9.0
完整实现代码
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter_map/flutter_map.dart'; import 'package:latlong2/latlong.dart'; class ImageTileViewer extends StatefulWidget { const ImageTileViewer({super.key}); @override State<ImageTileViewer> createState() => _ImageTileViewerState(); } class _ImageTileViewerState extends State<ImageTileViewer> { // 对应Leaflet中的配置参数 final mapMinZoom = 0.0; final mapMaxZoom = 4.0; final mapMaxResolution = 1.0; late final mapMinResolution = pow(2, mapMaxZoom) * mapMaxResolution; // 瓦片大小 final tileSize = 512; // 原图尺寸 宽7680 高4320 final imgWidth = 7680; final imgHeight = 4320; late final Crs customCrs; late final LatLngBounds mapBounds; @override void initState() { super.initState(); // 自定义Simple CRS,对应Leaflet中修改L.CRS.Simple的逻辑 customCrs = CrsSimple( // 对应Leaflet中的Transformation配置 transformation: Transformation(1, 0, -1, imgHeight.toDouble()), // 对应Leaflet中的scale方法 scale: (zoom) => pow(2, zoom) / mapMinResolution, // 对应Leaflet中的zoom方法 zoom: (scale) => log(scale * mapMinResolution) / ln2, ); // 计算地图边界,对应Leaflet中的fitBounds参数 final southwest = customCrs.latLngToPoint(LatLng(0, 0), mapMaxZoom); final northeast = customCrs.latLngToPoint(LatLng(imgHeight.toDouble(), imgWidth.toDouble()), mapMaxZoom); mapBounds = LatLngBounds( customCrs.pointToLatLng(southwest, mapMaxZoom), customCrs.pointToLatLng(northeast, mapMaxZoom), ); } @override Widget build(BuildContext context) { return Scaffold( body: FlutterMap( options: MapOptions( crs: customCrs, minZoom: mapMinZoom, maxZoom: mapMaxZoom, // 初始适配全图范围,对应Leaflet中的map.fitBounds initialCameraFit: CameraFit.bounds( bounds: mapBounds, padding: EdgeInsets.zero, ), // 限制拖动不超出图片范围 maxBounds: mapBounds, ), children: [ TileLayer( // 瓦片路径,和Leaflet配置一致 urlTemplate: '{z}/{x}/{y}.png', tileSize: tileSize.toDouble(), minZoom: mapMinZoom, maxZoom: mapMaxZoom, noWrap: true, tms: false, ), ], ), ); } }
配置调整说明
- 如果瓦片是本地资源,将
urlTemplate改为assets/{z}/{x}/{y}.png,同时在pubspec.yaml中声明对应资源路径 - 不需要限制拖动范围可以删除
maxBounds配置 - 需要开启PC端滚轮缩放删除
interactionOptions中对应配置即可
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

