Flutter可点击折线插件flutter_map_tappable_polyline的使用

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

Flutter Map Tappable Polyline

pub package

A Polyline with onTap event listener. This is a plugin for the flutter_map package.

Usage

To use flutter_map_tappable_polyline, add both flutter_map and flutter_map_tappable_polyline to your pubspec.yaml:

dependencies:
  flutter_map: ^6.0.1
  flutter_map_tappable_polyline: any # take latest version on Pub

Example Implementation

Here’s a complete example demonstrating how to use flutter_map_tappable_polyline in a Flutter application:

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_map_tappable_polyline/flutter_map_tappable_polyline.dart';
import 'package:latlong2/latlong.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Tappable Polyline Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: MyHomePage(title: 'Tappable Polyline Demo'),
    );
  }
}

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

  final String? title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<LatLng> getPoints(int index) {
    // Sample points for demonstration purposes
    if (index == 0) {
      return [
        LatLng(45.1313258, 5.5171205),
        LatLng(45.1313259, 5.5171206),
        LatLng(45.1313260, 5.5171207)
      ];
    } else if (index == 1) {
      return [
        LatLng(45.1313258, 5.5171205),
        LatLng(45.1313259, 5.5171208),
        LatLng(45.1313260, 5.5171209)
      ];
    }
    return [];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title!)),
      body: FlutterMap(
        options: MapOptions(initialCenter: LatLng(45.1313258, 5.5171205), initialZoom: 11.0),
        children: [
          TileLayer(
            urlTemplate: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
            subdomains: ['a', 'b', 'c'],
          ),
          TappablePolylineLayer(
            polylineCulling: true,
            pointerDistanceTolerance: 20,
            polylines: [
              TaggedPolyline(
                tag: 'My Polyline',
                points: getPoints(0),
                color: Colors.red,
                strokeWidth: 9.0,
              ),
              TaggedPolyline(
                tag: 'My 2nd Polyline',
                points: getPoints(1),
                color: Colors.black,
                strokeWidth: 3.0,
              ),
              TaggedPolyline(
                tag: 'My 3rd Polyline',
                points: getPoints(0),
                color: Colors.blue,
                strokeWidth: 3.0,
              ),
            ],
            onTap: (polylines, tapPosition) => print('Tapped: ' +
                polylines.map((polyline) => polyline.tag).join(',') +
                ' at ' +
                tapPosition.globalPosition.toString()),
            onMiss: (tapPosition) {
              print('No polyline was tapped at position ' +
                  tapPosition.globalPosition.toString());
            },
          )
        ],
      ),
    );
  }
}

Explanation

  • Dependencies: Ensure you have added flutter_map and flutter_map_tappable_polyline dependencies in your pubspec.yaml.
  • Map Initialization: Initialize your map using FlutterMap widget.
  • Tile Layer: Add a tile layer to render the base map.
  • Tappable Polyline Layer: Use TappablePolylineLayer to add clickable polylines to your map.
  • Handling Events: Implement onTap and onMiss callbacks to handle user interactions with polylines.

This setup will allow users to click on polylines displayed on the map, triggering the respective callback functions.


更多关于Flutter可点击折线插件flutter_map_tappable_polyline的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter可点击折线插件flutter_map_tappable_polyline的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用flutter_map_tappable_polyline插件来实现可点击折线的示例代码。这个插件允许你在flutter_map上绘制可交互的折线。

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

dependencies:
  flutter:
    sdk: flutter
  flutter_map: ^0.14.0  # 请检查最新版本
  flutter_map_tappable_polyline: ^0.2.3  # 请检查最新版本

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

接下来,在你的Flutter应用中,你可以按照以下步骤使用flutter_map_tappable_polyline插件:

  1. 导入必要的包
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'package:flutter_map_tappable_polyline/flutter_map_tappable_polyline.dart';
  1. 创建地图和可点击折线
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Flutter Map Tappable Polyline Demo')),
        body: MapScreen(),
      ),
    );
  }
}

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

class _MapScreenState extends State<MapScreen> {
  final MapController _controller = MapController();

  @override
  Widget build(BuildContext context) {
    return FlutterMap(
      mapController: _controller,
      options: MapOptions(
        center: LatLng(51.5, -0.09),
        zoom: 13.0,
      ),
      layers: [
        TileLayerOptions(
          urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
          subdomains: ['a', 'b', 'c'],
        ),
        TappablePolylineLayerOptions(
          polylines: [
            TappablePolyline(
              points: [
                LatLng(51.5074, -0.1278),
                LatLng(51.5027, -0.1331),
                LatLng(51.4964, -0.1298),
              ],
              color: Colors.blue,
              width: 4.0,
              onTap: (LatLng point) {
                // 在这里处理点击事件
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('Polyline tapped at: $point')),
                );
              },
            ),
          ],
        ),
      ],
    );
  }
}

在这个示例中:

  • 我们创建了一个FlutterMap,设置了地图的中心点和缩放级别。
  • 添加了一个TileLayerOptions来显示OpenStreetMap的图层。
  • 添加了一个TappablePolylineLayerOptions,其中包含了一条由几个LatLng点组成的可点击折线。
  • 当用户点击这条折线时,会触发onTap回调,显示一个SnackBar来通知用户点击的位置。

这个示例应该可以帮助你快速上手flutter_map_tappable_polyline插件的使用。如果你有更复杂的需求,比如多条折线、自定义样式或者不同的点击事件处理,可以基于这个示例进行扩展。

回到顶部