Flutter矢量地图插件vector_mbtiles的使用

发布于 1周前 作者 h691938207 来自 Flutter

Flutter矢量地图插件vector_mbtiles的使用

描述

VectorMBTiles 是一个用于在 FlutterMap 中处理 Mapbox 向量瓷砖的 Flutter 插件。

Screenshot_1654750708

特性

通过扩展 VectorTileProvider 并将 VectorMBTiles 作为 MemoryCacheVectorTileProvider 的参数传递,可以在内存中以高速运行。

开始使用

添加此包,请执行以下命令:

flutter pub add vector_mbtiles

使用示例

参考以下代码。详情请参阅 example 文件夹。

VectorTileLayerWidget(
    options: VectorTileLayerOptions(
        theme: Theme,
        tileProviders: TileProviders({
            'openmaptiles': VectorMBTilesProvider(
                mbtilesPath: '/path/to/mbtiles',
                maximumZoom: 18)
        })
    ),
)

以下是完整的示例 demo:

import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'package:vector_map_tiles/vector_map_tiles.dart';
import 'package:vector_mbtiles/vector_mbtiles.dart';
import 'package:vector_tile_renderer/vector_tile_renderer.dart'
    as vector_tile_renderer;

import 'osm_bright_ja_style.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'VectorMBTiles example',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'VectorMBTiles example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in
  // this case the title) provided by the parent (in this case the App widget)
  // and used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final MapController _mapController = MapController();

  [@override](/user/override)
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
        appBar: AppBar(
          // Here we take the value from the MyHomePage object that was created by
          // the App.build method, and use it to set our appbar title.
          title: Text(widget.title),
        ),
        body: Center(
          // Center is a layout widget. It takes a single child and positions it
          // in the middle of the parent.
          child: FlutterMap(
              mapController: _mapController,
              options: MapOptions(
                center: LatLng(35.68132332775388, 19.76712479771956),
                zoom: 15,
                maxZoom: 18,
                // plugins: [VectorMapTilesPlugin()],
              ),
              children: [
                VectorTileLayer(
                  key: const Key('VectorTileLayerWidget'),
                  theme: _mapTheme(context),
                  tileProviders: TileProviders(
                      {'openmaptiles': _cachingTileProvider(_basemapPath())}),
                ),
              ]),
        ));
  }
}

VectorTileProvider _cachingTileProvider(String mbtilesPath) {
  return MemoryCacheVectorTileProvider(
      delegate: VectorMBTilesProvider(
          mbtilesPath: mbtilesPath,
          // this is the maximum zoom of the provider, not the
          // maximum of the map. vector tiles are rendered
          // to larger sizes to support higher zoom levels
          maximumZoom: 14),
      maxSizeBytes: 1024 * 1024 * 2);
}

_mapTheme(BuildContext context) {
  // maps are rendered using themes
  // to provide a dark theme do something like this:
  // if (MediaQuery.of(context).platformBrightness == Brightness.dark) return myDarkTheme();
  return OSMBrightTheme.osmBrightJaTheme();
}

extension OSMBrightTheme on ProvidedThemes {
  static vector_tile_renderer.Theme osmBrightJaTheme({Logger? logger}) =>
      ThemeReader(logger: logger).read(osmBrightJaStyle());
}

String _basemapPath() {
  return 'assets/example.mbtiles';
}

更多关于Flutter矢量地图插件vector_mbtiles的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter矢量地图插件vector_mbtiles的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter中使用vector_mbtiles插件的示例代码。vector_mbtiles插件允许你在Flutter应用中加载和显示MBTiles格式的矢量地图。

首先,确保你已经在pubspec.yaml文件中添加了vector_mbtiles依赖:

dependencies:
  flutter:
    sdk: flutter
  vector_mbtiles: ^x.y.z  # 请替换为最新版本号

然后运行flutter pub get来安装依赖。

接下来,是一个简单的示例代码,展示如何在Flutter应用中加载和显示MBTiles地图:

import 'package:flutter/material.dart';
import 'package:vector_mbtiles/vector_mbtiles.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MapScreen(),
    );
  }
}

class MapScreen extends StatefulWidget {
  @override
  _MapScreenState createState() => _MapScreenState();
}

class _MapScreenState extends State<MapScreen> {
  late VectorMapController _mapController;

  @override
  void initState() {
    super.initState();
    // 初始化MBTiles地图控制器
    _mapController = VectorMapController(
      mbtilesAsset: 'assets/your_map.mbtiles', // 请替换为你的MBTiles文件路径
      initialZoom: 10,
      initialCenter: LatLng(0.0, 0.0), // 初始中心位置,请替换为实际位置
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Vector MBTiles Map'),
      ),
      body: VectorMap(
        controller: _mapController,
        options: VectorMapOptions(
          styles: [
            // 你可以在这里定义样式,例如道路、建筑物等的颜色
            {
              'layer': 'road',
              'paint': {
                'line-color': '#ffffff',
                'line-width': 2.0,
              },
            },
            // 添加更多样式...
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _mapController.dispose();
    super.dispose();
  }
}

在这个示例中,我们做了以下几件事:

  1. 依赖安装:在pubspec.yaml文件中添加了vector_mbtiles依赖。
  2. 地图控制器初始化:在initState方法中初始化了VectorMapController,并指定了MBTiles文件的路径、初始缩放级别和初始中心位置。
  3. 构建UI:使用VectorMap组件显示地图,并将地图控制器传递给它。同时,通过VectorMapOptions定义了一些基本的样式。
  4. 资源清理:在dispose方法中释放了地图控制器资源。

请确保你的MBTiles文件已经放在了项目的assets目录下,并在pubspec.yaml文件中声明了资源:

flutter:
  assets:
    - assets/your_map.mbtiles

这个示例代码提供了一个基本的框架,你可以根据需要进一步扩展和自定义地图的样式和功能。

回到顶部