如何在google_maps_flutter包中使用tileOverlays?

3

使用Java,我们可以利用瓦片叠加将WMS瓦片放置在谷歌基础地图之上。在Flutter中,我发现google_maps_flutter的构造函数具有tileOverlays属性,但很难找到有效的示例。这里有没有人成功地在Flutter中将WMS瓦片叠加在谷歌地图之上?


您可以使用定位小部件简单地堆叠任意数量的小部件。 - Ayyaz meo
您可以在此处检查google_maps_flutter包中的示例:https://github.com/flutter/plugins/blob/master/packages/google_maps_flutter/google_maps_flutter/example/lib/tile_overlay.dart - jabamataro
1个回答

10
我成功让它工作了。

背景如下:

我需要展示由无人机图像创建的自定义瓦片。目标是在缩放级别14到22之间获得更好的图像分辨率。

我必须使用的 API 没有整个地图的图像,这是有道理的,因为我们只关心一些区域的细节。

但是,我可以在 API 上获取 KML 图层文件,这使我能够事先知道可以获取哪些图像。

这些 KML 文件定义了我可以从 API 下载的瓦片的坐标。

解决方案

1)

第一步是获取这些 KML 文件并解析它们,以找出哪些区域被无人机图像覆盖。(这不是重点,但如果您希望,我可以向您展示)

2)

然后我创建了一个自定义的瓷砖提供者。你基本上需要覆盖一个名为getTile的方法。

这个方法必须返回一个瓷砖。 在Flutter中,瓷砖基本上是一个包含宽度、高度和数据(以Uint8List形式)的对象。

import 'package:google_maps_flutter/google_maps_flutter.dart';

class TestTileProvider implements TileProvider{
  @override
  Future<Tile> getTile(int x, int y, int zoom) {
    // TODO: implement getTile
    throw UnimplementedError();
  }

}

那些数据可以通过在画布上绘制来轻松创建,正如官方示例所建议的那样。
  @override
  Future<Tile> getTile(int x, int y, int? zoom) async {
    final ui.PictureRecorder recorder = ui.PictureRecorder();
    final Canvas canvas = Canvas(recorder);
    final TextSpan textSpan = TextSpan(
      text: '$x,$y',
      style: textStyle,
    );
    final TextPainter textPainter = TextPainter(
      text: textSpan,
      textDirection: TextDirection.ltr,
    );
    textPainter.layout(
      minWidth: 0.0,
      maxWidth: width.toDouble(),
    );
    final Offset offset = const Offset(0, 0);
    textPainter.paint(canvas, offset);
    canvas.drawRect(
        Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), boxPaint);
    final ui.Picture picture = recorder.endRecording();
    final Uint8List byteData = await picture
        .toImage(width, height)
        .then((ui.Image image) =>
            image.toByteData(format: ui.ImageByteFormat.png))
        .then((ByteData? byteData) => byteData!.buffer.asUint8List());
    return Tile(width, height, byteData);
  }


问题在于它不能满足我的需求,因为我需要显示真实图片而不是在瓷砖上绘制边框和瓷砖坐标。我找到了一种方法来加载网络图片并将它们转换为适合瓷砖的正确格式。
final uri = Uri.https(AppUrl.BASE, imageUri);
try {
  final ByteData imageData = await NetworkAssetBundle(uri).load("");
  final Uint8List bytes = imageData.buffer.asUint8List();
  return Tile(TILE_SIZE, TILE_SIZE, bytes);
} catch (e) {}

然而,由于我没有整张地图的图片,所以在没有图片可用时,我必须返回一些东西。我制作了一个透明的瓷砖,并在需要时返回它。为了提高性能,我在创建提供程序时创建透明瓷砖,然后始终返回相同的瓷砖。
class TestTileProvider implements TileProvider {
  static const int TILE_SIZE = 256;
  static final Paint boxPaint = Paint();
  Tile transparentTile;
...
  TestTileProvider() {
    boxPaint.isAntiAlias = true;
    boxPaint.color = Colors.transparent;
    boxPaint.style = PaintingStyle.fill;
    initTransparentTile();
  }
...

  void initTransparentTile() async {
    final ui.PictureRecorder recorder = ui.PictureRecorder();
    final Canvas canvas = Canvas(recorder);
    canvas.drawRect(
        Rect.fromLTRB(0, 0, TILE_SIZE.toDouble(), TILE_SIZE.toDouble()),
        boxPaint);
    final ui.Picture picture = recorder.endRecording();
    final Uint8List byteData = await picture
        .toImage(TILE_SIZE, TILE_SIZE)
        .then((ui.Image image) =>
            image.toByteData(format: ui.ImageByteFormat.png))
        .then((ByteData byteData) => byteData.buffer.asUint8List());
    transparentTile = Tile(TILE_SIZE, TILE_SIZE, byteData);
  }
...

}

下一个遇到的问题是,这个getTile方法只能给你在瓦片世界中的瓦片坐标(xyzoom)。而在KML图层中定义的位置是以度数来定义的。
<LatLonAltBox>
    <north>47.054785</north>
    <south>47.053557</south>
    <east>6.780674</east>
    <west>6.774709</west>
</LatLonAltBox>

(那些是虚假的坐标,我不能向您展示真实的坐标 :))

我非常、非常、非常建议您阅读此文以了解所有这些坐标类型之间的区别。

然后我不得不找到一种将瓷砖坐标转换为度数的方法。

由于在Flutter中我找不到检索投影对象的方式(在javascript API中有一种检索它的方式)。因此我不得不自己转换这些坐标。

首先,我必须了解它们是如何从度数转换为瓦片坐标的(这使用了墨卡托投影和一些数学知识)。

幸运的是,我能够在这里找到JS实现{{link4:project方法}}。

我所要做的“唯一”事情就是反转它,这样我就可以从瓦片坐标获得度数。

我首先重写了project方法,然后对其进行了反转:
// The mapping between latitude, longitude and pixels is defined by the web
  // mercator projection.
  // Source: https://developers.google.com/maps/documentation/javascript/examples/map-coordinates?csw=1
  math.Point project(LatLng latLng) {
    double siny = math.sin((latLng.latitude * math.pi) / 180);

    // Truncating to 0.9999 effectively limits latitude to 89.189. This is
    // about a third of a tile past the edge of the world tile.
    siny = math.min(math.max(siny, -0.9999), 0.9999);

    return new math.Point(
      TILE_SIZE * (0.5 + latLng.longitude / 360),
      TILE_SIZE * (0.5 - math.log((1 + siny) / (1 - siny)) / (4 * math.pi)),
    );
  }

  LatLng reverseMercatorFromTileCoordinates(int x, int y, int zoom) {
    // Reverse mercator projection.
    // Reverse of above function (kept for readibility)
    //
    // 1) Compute longitude
    //
    // TILE_SIZE * (0.5 + latLng.longitude / 360) = x
    //0.5 + latLng.longitude / 360 = x / TILE_SIZE
    // latLng.longitude / 360 = x / TILE_SIZE - 0.5
    // latLng.longitude = (x / TILE_SIZE - 0.5) *360

    int pixelCoordinateX = x * TILE_SIZE;
    int pixelCoordinateY = y * TILE_SIZE;

    double worldCoordinateX = pixelCoordinateX / math.pow(2, zoom);
    double worldCoordinateY = pixelCoordinateY / math.pow(2, zoom);

    double long = (worldCoordinateX / TILE_SIZE - 0.5) * 360;

    //
    // 2) compute sin(y)
    //
    // TILE_SIZE * (0.5 - math.log((1 + siny) / (1 - siny)) / (4 * math.pi)) = y
    // 0.5 - math.log((1 + siny) / (1 - siny)) / (4 * math.pi) = y / TILE_SIZE
    // math.log((1 + siny) / (1 - siny)) / (4 * math.pi) = -(y / TILE_SIZE) + 0.5
    // math.log((1 + siny) / (1 - siny)) = (-(y / TILE_SIZE) + 0.5)(4 * math.pi)
    // (1 + siny) / (1 - siny) = math.pow(math.e, (-(y / TILE_SIZE) + 0.5)(4 * math.pi))
    // siny = (math.pow(math.e, (-(y / TILE_SIZE) + 0.5)(4 * math.pi)) - 1) / (1+math.pow(math.e, (-(y / TILE_SIZE) + 0.5)(4 * math.pi)));
    double part = math.pow(
        math.e, ((-(worldCoordinateY / TILE_SIZE) + 0.5) * (4 * math.pi)));
    double siny = (part - 1) / (1 + part);
    //
    // 3) Compute latitude
    //
    // siny = math.sin((latLng.latitude * math.pi) / 180)
    // math.asin(siny) = (latLng.latitude * math.pi) / 180
    // math.asin(siny) * 180 = (latLng.latitude * math.pi)
    // (math.asin(siny) * 180) / math.pi = latLng.latitude
    double lat = (math.asin(siny) * 180) / math.pi;
    return LatLng(lat, long);
  }

我现在能够检查提供者请求的瓷砖是否在无人机图像覆盖区域内!以下是完整的getTile实现:
  @override
  Future<Tile> getTile(int x, int y, int zoom) async {

    // Reverse tile coordinates to degreees
    LatLng tileNorthWestCornerCoordinates =
        reverseMercatorFromTileCoordinates(x, y, zoom);

    // `domain` is an object in which are stored the kml datas fetched before
    KMLLayer kmlLayer =
        domain.getKMLLayerforPoint(tileNorthWestCornerCoordinates);

    
    if (kmlLayer != null &&
        zoom >= kmlLayer.minZoom &&
        zoom <= kmlLayer.maxZoom) {
      final String imageUri = domain.getImageUri(kmlLayer, x, y, zoom);

      final uri = Uri.https(AppUrl.BASE, imageUri);
      try {
        final ByteData imageData = await NetworkAssetBundle(uri).load("");
        final Uint8List bytes = imageData.buffer.asUint8List();
        return Tile(TILE_SIZE, TILE_SIZE, bytes);
      } catch (e) {}
    }
    // return transparent tile
    return transparentTile;
  }

完整的 TileProvider 示例代码如下:

import 'dart:math' as math;
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:app_digivitis/core/constants/app_url.dart';
import 'package:app_digivitis/core/models/domain.dart';
import 'package:app_digivitis/core/models/kml_layer.dart';
import 'package:app_digivitis/core/viewmodels/screens/user_view_model.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:provider/provider.dart';

class TestTileProvider implements TileProvider {
  static const int TILE_SIZE = 256;
  static final Paint boxPaint = Paint();
  BuildContext context;
  Tile transparentTile;
  Domain domain;

  TestTileProvider() {
    boxPaint.isAntiAlias = true;
    boxPaint.color = Colors.transparent;
    boxPaint.style = PaintingStyle.fill;
    initTransparentTile();
  }

  @override
  Future<Tile> getTile(int x, int y, int zoom) async {
    // Reverse tile coordinates to degreees
    LatLng tileNorthWestCornerCoordinates =
        reverseMercatorFromTileCoordinates(x, y, zoom);

    // `domain` is an object in which are stored the kml datas fetched before
    KMLLayer kmlLayer =
        domain.getKMLLayerforPoint(tileNorthWestCornerCoordinates);

    if (kmlLayer != null &&
        zoom >= kmlLayer.minZoom &&
        zoom <= kmlLayer.maxZoom) {
      final String imageUri = domain.getImageUri(kmlLayer, x, y, zoom);

      final uri = Uri.https(AppUrl.BASE, imageUri);
      try {
        final ByteData imageData = await NetworkAssetBundle(uri).load("");
        final Uint8List bytes = imageData.buffer.asUint8List();
        return Tile(TILE_SIZE, TILE_SIZE, bytes);
      } catch (e) {}
    }
    // return transparent tile
    return transparentTile;
  }

  void initContext(BuildContext context) {
    context = context;
    final userViewModel = Provider.of<UserViewModel>(context, listen: false);
    domain = userViewModel.domain;
  }

  void initTransparentTile() async {
    final ui.PictureRecorder recorder = ui.PictureRecorder();
    final Canvas canvas = Canvas(recorder);
    canvas.drawRect(
        Rect.fromLTRB(0, 0, TILE_SIZE.toDouble(), TILE_SIZE.toDouble()),
        boxPaint);
    final ui.Picture picture = recorder.endRecording();
    final Uint8List byteData = await picture
        .toImage(TILE_SIZE, TILE_SIZE)
        .then((ui.Image image) =>
            image.toByteData(format: ui.ImageByteFormat.png))
        .then((ByteData byteData) => byteData.buffer.asUint8List());
    transparentTile = Tile(TILE_SIZE, TILE_SIZE, byteData);
  }

  // The mapping between latitude, longitude and pixels is defined by the web
  // mercator projection.
  // Source: https://developers.google.com/maps/documentation/javascript/examples/map-coordinates?csw=1
  math.Point project(LatLng latLng) {
    double siny = math.sin((latLng.latitude * math.pi) / 180);

    // Truncating to 0.9999 effectively limits latitude to 89.189. This is
    // about a third of a tile past the edge of the world tile.
    siny = math.min(math.max(siny, -0.9999), 0.9999);

    return new math.Point(
      TILE_SIZE * (0.5 + latLng.longitude / 360),
      TILE_SIZE * (0.5 - math.log((1 + siny) / (1 - siny)) / (4 * math.pi)),
    );
  }

  LatLng reverseMercatorFromTileCoordinates(int x, int y, int zoom) {
    // Reverse mercator projection.
    // Reverse of above function (kept for readibility)
    //
    // 1) Compute longitude
    //
    // TILE_SIZE * (0.5 + latLng.longitude / 360) = x
    //0.5 + latLng.longitude / 360 = x / TILE_SIZE
    // latLng.longitude / 360 = x / TILE_SIZE - 0.5
    // latLng.longitude = (x / TILE_SIZE - 0.5) *360

    int pixelCoordinateX = x * TILE_SIZE;
    int pixelCoordinateY = y * TILE_SIZE;

    double worldCoordinateX = pixelCoordinateX / math.pow(2, zoom);
    double worldCoordinateY = pixelCoordinateY / math.pow(2, zoom);

    double long = (worldCoordinateX / TILE_SIZE - 0.5) * 360;

    //
    // 2) compute sin(y)
    //
    // TILE_SIZE * (0.5 - math.log((1 + siny) / (1 - siny)) / (4 * math.pi)) = y
    // 0.5 - math.log((1 + siny) / (1 - siny)) / (4 * math.pi) = y / TILE_SIZE
    // math.log((1 + siny) / (1 - siny)) / (4 * math.pi) = -(y / TILE_SIZE) + 0.5
    // math.log((1 + siny) / (1 - siny)) = (-(y / TILE_SIZE) + 0.5)(4 * math.pi)
    // (1 + siny) / (1 - siny) = math.pow(math.e, (-(y / TILE_SIZE) + 0.5)(4 * math.pi))
    // siny = (math.pow(math.e, (-(y / TILE_SIZE) + 0.5)(4 * math.pi)) - 1) / (1+math.pow(math.e, (-(y / TILE_SIZE) + 0.5)(4 * math.pi)));
    double part = math.pow(
        math.e, ((-(worldCoordinateY / TILE_SIZE) + 0.5) * (4 * math.pi)));
    double siny = (part - 1) / (1 + part);
    //
    // 3) Compute latitude
    //
    // siny = math.sin((latLng.latitude * math.pi) / 180)
    // math.asin(siny) = (latLng.latitude * math.pi) / 180
    // math.asin(siny) * 180 = (latLng.latitude * math.pi)
    // (math.asin(siny) * 180) / math.pi = latLng.latitude
    double lat = (math.asin(siny) * 180) / math.pi;
    return LatLng(lat, long);
  }
}

请不要过多关注上下文,因为我需要它来使用提供者检索我的domain实例。

3)

使用这个提供者!

完整的带地图示例小部件:

import 'package:app_digivitis/core/providers/test_provider.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';

class MarksMapTest extends StatefulWidget {
  @override
  _MarksMapTestState createState() => _MarksMapTestState();
}

class _MarksMapTestState extends State<MarksMapTest>
    with SingleTickerProviderStateMixin {
  GoogleMapController mapController;
  Location _location = Location();
  LocationData _center =
      LocationData.fromMap({'latitude': 51.512153, 'longitude': -0.111019});
  TileOverlay _tileOverlay;
  TestTileProvider testTileProvider = TestTileProvider();

  @override
  void initState() {
    super.initState();
    createTileOverlay();
    _location.getLocation().then((value) {
      _center = value;
    });
  }

  void createTileOverlay() {
    if (_tileOverlay == null) {
      final TileOverlay tileOverlay = TileOverlay(
        tileOverlayId: TileOverlayId('tile_overlay_1'),
        tileProvider: testTileProvider,
      );
      _tileOverlay = tileOverlay;
    }
  }

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
    centerMap(location: _center);
  }

  void centerMap({LocationData location}) async {
    if (location == null) location = await _location.getLocation();
    mapController.animateCamera(
      CameraUpdate.newCameraPosition(CameraPosition(
          target: LatLng(location.latitude, location.longitude), zoom: 14)),
    );
  }

  @override
  Widget build(BuildContext context) {
    testTileProvider.initContext(context);
    Set<TileOverlay> overlays = <TileOverlay>{
      if (_tileOverlay != null) _tileOverlay,
    };
    return Scaffold(
      body: GoogleMap(
        onMapCreated: (controller) => _onMapCreated(controller),
        initialCameraPosition: CameraPosition(
          target: LatLng(_center.latitude, _center.longitude),
          zoom: 14.0,
        ),
        tileOverlays: overlays,
        mapType: MapType.hybrid,
        myLocationButtonEnabled: false,
        myLocationEnabled: true,
        zoomControlsEnabled: false,
        mapToolbarEnabled: false,
      ),
    );
  }
}


谢谢Maël,但我如何添加自定义瓷砖URL? - Sos.
1
你是什么意思?@زياد - Maël Pedretti
你能采纳我的答案吗?这将为其他可能需要此主题答案的用户提供更多的可见性。@زياد - Maël Pedretti
@MaëlPedretti 你好,能分享一下这整段代码吗? - Tim Mwaura
嘿@TimMwaura,这个项目是一个企业级项目,所以恐怕我无法完成它,但如果你能找到一个开放的无人机图像数据库,我可以制作另一个示例。 - Maël Pedretti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接