Last active
August 21, 2024 08:19
-
-
Save Pyozer/1bd27fbecfb6f4c4efc0b08a32ec166e to your computer and use it in GitHub Desktop.
Create polygons on map touch using Flutter_Map lib
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import 'package:flutter/material.dart'; | |
| import 'package:flutter_map/plugin_api.dart'; | |
| import 'package:latlong/latlong.dart'; | |
| const kMarker = "https://www.sccpre.cat/png/big/16/164026_map-marker-png.png"; | |
| class MapScreen extends StatefulWidget { | |
| MapScreen({Key key}) : super(key: key); | |
| _MapScreenState createState() => _MapScreenState(); | |
| } | |
| class _MapScreenState extends State<MapScreen> { | |
| List<LatLng> _touches = []; | |
| List<Polygon> _polygons = []; | |
| void _addMarker(LatLng pos) { | |
| setState(() => _touches.add(pos)); | |
| } | |
| Polygon _buildPolygonFromTouches() { | |
| return Polygon( | |
| points: _touches.map((p) => LatLng(p.latitude, p.longitude)).toList(), | |
| borderColor: Colors.black, | |
| borderStrokeWidth: 3.0, | |
| color: Colors.black26, | |
| isDotted: true, | |
| ); | |
| } | |
| void _onMarkerTap(LatLng pos, bool isFirst) { | |
| if (!isFirst) return; | |
| _touches.add(pos); | |
| _polygons.add(_buildPolygonFromTouches()); | |
| _touches.clear(); | |
| setState(() {}); // Force rebuild | |
| } | |
| List<Marker> _buildMarkers() { | |
| List<Marker> markers = []; | |
| for (var i = 0; i < _touches.length; i++) { | |
| final pos = _touches[i]; | |
| markers.add(Marker( | |
| width: 30.0, | |
| height: 30.0, | |
| point: pos, | |
| builder: (_) => GestureDetector( | |
| onTap: () => _onMarkerTap(pos, i == 0), | |
| onLongPress: () => setState(() => _touches.removeAt(i)), | |
| child: Image.network(kMarker), | |
| ), | |
| )); | |
| } | |
| return markers; | |
| } | |
| @override | |
| Widget build(BuildContext context) { | |
| return FlutterMap( | |
| options: MapOptions( | |
| center: LatLng(51.5, -0.09), | |
| zoom: 13.0, | |
| onTap: _addMarker, | |
| ), | |
| layers: [ | |
| TileLayerOptions( | |
| urlTemplate: "https://api.tiles.mapbox.com/v4/" | |
| "{id}/{z}/{x}/{y}@2x.png?access_token={accessToken}", | |
| additionalOptions: { | |
| 'accessToken': | |
| 'pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', | |
| 'id': 'mapbox.streets', | |
| }, | |
| ), | |
| PolygonLayerOptions(polygons: _polygons), | |
| MarkerLayerOptions(markers: _buildMarkers()), | |
| ], | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment