Stateful map controller for Flutter Map

Related tags

Map map_controller
Overview

Map controller

pub package

Stateful map controller for Flutter Map. Manage markers, lines and polygons.

View the web demo

Usage

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong/latlong.dart';
import 'package:map_controller/map_controller.dart';

class _MapPageState extends State<MapPage> {
  MapController mapController;
  StatefulMapController statefulMapController;
  StreamSubscription<StatefulMapControllerStateChange> sub;

  @override
  void initState() {
    // intialize the controllers
    mapController = MapController();
    statefulMapController = StatefulMapController(mapController: mapController);

    // wait for the controller to be ready before using it
    statefulMapController.onReady.then((_) => print("The map controller is ready")));

    /// [Important] listen to the changefeed to rebuild the map on changes:
    /// this will rebuild the map when for example addMarker or any method 
    /// that mutates the map assets is called
    sub = statefulMapController.changeFeed.listen((change) => setState(() {}));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child: Stack(children: <Widget>[
        FlutterMap(
          mapController: mapController,
          options: MapOptions(center: LatLng(48.853831, 2.348722), zoom: 11.0),
          layers: [
            MarkerLayerOptions(markers: statefulMapController.markers),
            PolylineLayerOptions(polylines: statefulMapController.lines),
            PolygonLayerOptions(polygons: statefulMapController.polygons)
          ],
        ),
        // ...
      ])),
    );
  }

  @override
  void dispose() {
    sub.cancel();
    super.dispose();
  }
}

class MapPage extends StatefulWidget {
  @override
  _MapPageState createState() => _MapPageState();
}

Api

Api for the StatefulMapController class

Map controls

Zoom

zoom: get the current zoom value

zoomIn(): increase the zoom level by 1

zoomOut(): decrease the zoom level by 1

zoomTo(Double value): zoom to the provided value

Center

center: get the current center LatLng value

centerOnPoint(LatLng point): center on the LatLng value

Map assets

Markers

addMarker(String name, Marker marker): add a named marker on the map

addMarkers(Map<String, Marker> markers): add several named markers on the map

removeMarker(String name, Marker marker): remove a named marker from the map

removeMarkers(Map<String, Marker> markers): remove several named markers from the map

markers: get the markers that are on the map

namedMarkers: get the markers with their names that are on the map

Stateful markers

New in 0.7: the stateful makers hold their own state and can be mutated

statefulMapController.addStatefulMarker(
   name: "some marker",
   statefulMarker: StatefulMarker(
      height: 80.0,
      width: 120.0,
      state: <String, dynamic>{"showText": false},
      point: LatLng(48.853831, 2.348722),
      builder: (BuildContext context, Map<String, dynamic> state) {
         Widget w;
         final markerIcon = IconButton(
            icon: const Icon(Icons.location_on),
            onPressed: () => statefulMapController.mutateMarker(
                  name: "some marker",
                  property: "showText",
                  value: !(state["showText"] as bool)));
         if (state["showText"] == true) {
            w = Column(children: <Widget>[
            markerIcon,
            Container(
                  color: Colors.white,
                  child: Padding(
                     padding: const EdgeInsets.all(5.0),
                     child: Text(place.name, textScaleFactor: 1.3))),
            ]);
         } else {
            w = markerIcon;
         }
         return w;
      })
   );

Lines

addLine(String name, List<LatLng> points, double width = 1.0, Color color = Colors.green, bool isDotted = false): add a line on the map

lines: get the lines that are on the map

Polygons

addPolygon(String name, List<LatLng> points, double width = 1.0, Color color = const Color(0xFF00FF00), double borderWidth = 0.0, Color borderColor = const Color(0xFFFFFF00)): add a polygon on the map

polygons: get the polygons that are on the map

On ready callback

Execute some code right after the map is ready:

@override
void initState() {
   statefulMapController.onReady.then((_) {
      setState((_) =>_ready = true);
   });
   super.initState();
}

Changefeed

A changefeed is available: it's a stream with all state changes from the map controller. Use it to update the map when a change occurs:

statefulMapController.onReady.then((_) {
    statefulMapController.changeFeed.listen((change) => setState(() {}));
   });
}

Geojson data

The map controller can draw on the map from geojson data:

void loadData() async {
  print("Loading geojson data");
  final data = await rootBundle.loadString('assets/airports.geojson');
  await statefulMapController.fromGeoJson(data,
    markerIcon: Icon(Icons.local_airport), verbose: true);
}

@override
void initState() {
  mapController = MapController();
  statefulMapController = StatefulMapController(mapController: mapController);
  statefulMapController.onReady.then((_) => loadData());
  sub = statefulMapController.changeFeed.listen((change) => setState(() {}));
  super.initState();
}

Tile layer management

Some predefined tile layers are available.

FlutterMap(
   mapController: mapController,
   options: MapOptions(
      center: LatLng(48.853831, 2.348722), zoom: 11.0),
   layers: [
      // Use the map controller's tile layer
      statefulMapController.tileLayer,
      MarkerLayerOptions(markers: statefulMapController.markers),
      // ...
   ],
)

To switch tile layers at runtime use:

statefulMapController.switchTileLayer(TileLayerType.monochrome);

Available layers:

TileLayerType.normal
TileLayerType.topography
TileLayerType.monochrome
TileLayerType.hike

A tile layers bar is available:

Stack(children: <Widget>[
   FlutterMap(
      mapController: mapController,
      options: MapOptions(center: LatLng(48.853831, 2.348722), zoom: 11.0),
      layers: [
      statefulMapController.tileLayer,
      MarkerLayerOptions(markers: statefulMapController.markers),
      ],
   ),
   Positioned(
      top: 15.0,
      right: 15.0,
      child: TileLayersBar(controller: statefulMapController))
])
Comments
  • Version issues

    Version issues

    C:\flutter\bin\flutter.bat --no-color pub get Running "flutter pub get" in NextTripMobile...

    Because map_controller >=0.8.0 depends on rxdart ^0.24.1 and [YOUR_APP_NAME] depends on rxdart ^0.25.0, map_controller >=0.8.0 is forbidden. So, because [YOUR_APP_NAME] depends on map_controller ^0.8.0, version solving failed. pub get failed (1; So, because [YOUR_APP_NAME] depends on map_controller ^0.8.0, version solving failed.)

    Process finished with exit code 1

    opened by joao10martins 3
  • Problem with sample usage code

    Problem with sample usage code

    When I run the sample usage code, I noticed a problem at line 24.

    There seems to be an extra parathesis

    /// [Important] listen to the changefeed to rebuild the map on changes:
    /// this will rebuild the map when for example addMarker or any method 
    /// that mutates the map assets is called
    sub = statefulMapController.changeFeed.listen((change) => setState(() {})); //  <- Extra closing brace paranthesis here 
    

    What am I missing?

    Warmest,

    opened by ElasticBottle 2
  • Cannot rotate map by gesture

    Cannot rotate map by gesture

    Without setting the rotation directly on mapOption. The map cannot just rotate intuitively by gesture with 2 fingers. Is this a bug or missing feature/config? image

    opened by carlchandev 1
  • Run dart migration to arrive at null safety

    Run dart migration to arrive at null safety

    In order to use this with the latest version of flutter_map, I needed to update this library to be null safe. Feel free to comment/modify, but this is a first pass at that migration.

    opened by mpinkard 0
  • statefulMapController.addMarker dit not Display on the map

    statefulMapController.addMarker dit not Display on the map

    I call statefulMapController.addMarker Method in onTap event callback, but the marker dit not appear on my map even if setState(){} after addMarker Method

    opened by 244226077 0
  • Version issues again

    Version issues again

    Because map_controller >=0.9.0 depends on flutter_map ^0.11.0 and MyApp depends on flutter_map ^0.14.0, map_controller >=0.9.0 is forbidden. So, because MyApp depends on map_controller 0.9.0, version solving failed.

    opened by LondonJammo 1
  • null safety

    null safety

    Please migrate to using null safety: https://dart.dev/null-safety/migration-guide

    Dependencies:

    • flutter_map itself is in the process: https://github.com/fleaflet/flutter_map/pull/870 It can already be used via a branch: https://github.com/fleaflet/flutter_map/issues/829#issuecomment-819813228
    • latlong2 can be used instead of deprecated latlong, as flutter_map does: https://github.com/fleaflet/flutter_map/blob/master/pubspec.yaml#L14
    • geojson is not null safe yet: https://github.com/synw/geojson/issues/37 (geojson_vi is)
    • geopoint has a pull request: https://github.com/synw/geopoint/pull/8
    • pedantic is null safe
    • rxdart is null safe
    • extra_pedantic is null safe

    @synw has no time (https://github.com/synw/geojson/issues/37#issuecomment-843467147) so maybe someone else can take it on? Unfortunately I am a flutter noob (JavaScript dev) and don't feel up to it.

    opened by barbalex 4
Releases(0.9.0)
Owner
"All that is gold does not glitter, not all those who wander are lost". Tolkien
null
Custom map markers - Custom Map Markers Using Flutter

Custom Map Markers Not only "Everything is a widget" also "Everywhere is a widge

null 8 Oct 19, 2022
A new flutter plugin for mapbox. You can use it for your map backgrounds inside flutter applications

A new flutter plugin for mapbox. You can use it for your map backgrounds inside flutter applications

Boris Gautier 5 Sep 14, 2022
A flutter package for select a city from svg map.

City Picker From Map A flutter package for select a city from svg map. Supported countries (+150) are here. Screenshots Getting Started In the pubspec

Ahmet ÇELİK 49 Nov 17, 2022
Flutter Tutorial - Google Map with Live Location Tracking

Flutter Tutorial - Google Map with Live Location Tracking Build Google Map app with Live Location Tracking in Flutter. ✌   App Preview Android Preview

Samuel Adekunle 10 Dec 22, 2022
Map Picker for Flutter

Map Pin Picker A Vendor-free map Library for Easy and Quick Usage. Follow the steps to integrate Google Maps (https://pub.dev/packages/google_maps_flu

Akbar 16 Jul 15, 2022
Flutter Google Map Example - Day 41

Flutter Google Map Example - Day 41 class Afgprogrammer extends Flutter100DaysOfCode { video() { return { "title": "Flutter Google Map Exa

Mohammad Rahmani 74 Jan 3, 2023
Flutter plugin to display a simple flat world map with animated points in real time

Flutter Simple Map Flutter plugin to display a simple flat world map with animated points in real time. Can be used as a presentation of online users,

Vladyslav Korniienko 7 Dec 8, 2022
A Flutter map widget inspired by Leaflet

flutter_map A Dart implementation of Leaflet for Flutter apps. Installation Add flutter_map to your pubspec: dependencies: flutter_map: any # or the

null 2.2k Dec 28, 2022
🌍 Map location picker component for flutter Based on google_maps_flutter

google_map_location_picker Location picker using the official google_maps_flutter. I made This plugin because google deprecated Place Picker. Using Pu

Ibrahim Eid 189 Dec 5, 2022
A map widget with live position updates for Flutter

Livemap A map widget with live position updates. Based on Flutter map and Geolocator. Provides a controller api to handle map state changes. Example i

null 45 Sep 28, 2022
Flutter Google Map Example

Flutter Google Map Example A Flutter application demonstrate google map. Preview Listener and Marker Compass MapTypes Plugin google_maps_flutter from

Bhavik Makwana 67 Sep 14, 2021
A Flutter package for place search using MapBox Api and for Static map image

About This package provides easy api calls to MapBox Search API. Also, it contains an static map image generator ?? . Maki Icons can be used now in ma

Ketan Choyal 63 Dec 2, 2022
How To Integrate Customized Google Map in Flutter

How To Integrate Customized Google Map in Flutter Let’s develop a customised Google Maps for the best user experience. Visit : https://medium.com/flut

Jaimil Patel 19 Dec 6, 2022
A Flutter map widget inspired by Leaflet

flutter_map A Dart implementation of Leaflet for Flutter apps. Usage Add flutter_map to your pubspec: dependencies: flutter_map: any # or the latest

AppTree Software, Inc 114 Dec 13, 2022
Flutter Aris Map Application

Flutter Aris Map Application Version 1️⃣ . 0️⃣ . 0️⃣ ➕ 1️⃣ 4️⃣ Getting Started $ git clone https://github.com/ariscybertech/aris_map.git $ flutter pac

Behruz Hurramov 4 Dec 22, 2022
A Flutter map widget inspired by Leaflet

flutter_map A Dart implementation of Leaflet for Flutter apps. Installation Add flutter_map to your pubspec: dependencies: flutter_map: any # or the

null 2.2k Jan 3, 2023
A google map example for flutter

Flutter Google Map Example - Day 41 class Afgprogrammer extends Flutter100DaysOf

Behruz Hurramov 5 Nov 24, 2022
Customized google map with widget markers. Enables to show markers with widget code.

widget_marker_google_map Google map with widget markers. Set up Follow the steps on google_maps_flutter document. Usage Same as google_maps_flutter ex

Santa Takahashi 8 Dec 4, 2022
Plugin for 'flutter_map' providing advanced caching functionality, with ability to download map regions for offline use. Also includes useful prebuilt widgets.

flutter_map_tile_caching A plugin for the flutter_map library to provide an easy way to cache tiles and download map regions for offline use. Installa

Luka S 69 Jan 3, 2023