OpenStreetMap plugin for flutter

Overview

flutter_osm_plugin

pub

Platform Support

Android iOS Web
supported ✔️ supported ✔️ (min iOS supported : 12) under-development

osm plugin for flutter apps

  • current position (Android/iOS)
  • change position (Android/iOS)
  • create Marker manually (Android/iOS)
  • tracking user location (Android/iOS)
  • customize Icon Marker (Android/iOS)
  • customize user Marker (Android/iOS)
  • assisted selection position (Android/iOS)
  • set BoundingBox (Android)
  • zoom into regon (Android/iOS)
  • draw Road,recuperate information (duration/distance) of the current road (Android/iOS)
  • draw Road manually (Android/iOS)
  • ClickListener on Marker (Android/iOS)
  • ClickListener on Map (Android/iOS)
  • calculate distance between 2 points
  • address suggestion
  • draw shapes (Only Android)
  • simple dialog location picker (Android/iOS)
  • listen to region change (Android/iOS)

Getting Started

openStreetMap flutter examples

openStreetMap flutter examples

Installing

Add the following to your pubspec.yaml file:

dependencies:
  flutter_osm_plugin: ^0.28.2

Migration to 0.16.0 (Android Only)

if you are using this plugin before Flutter 2

you should make some modification in build.gradle before that run flutter clean && flutter pub get

open file build.gradle inside android file

* change kotlin version from `1.4.21` to `1.5.21`
* change gradle version from `4.1.1` to `7.0.2`

Simple Usage

Creating a basic OSMFlutter :

 OSMFlutter( 
        controller:mapController,
        trackMyPosition: false,
        initZoom: 12,
        minZoomLevel: 8,
        maxZoomLevel: 14,
        stepZoom: 1.0,
        userLocationMarker: UserLocationMaker(
            personMarker: MarkerIcon(
                icon: Icon(
                    Icons.location_history_rounded,
                    color: Colors.red,
                    size: 48,
                ),
            ),
            directionArrowMarker: MarkerIcon(
                icon: Icon(
                    Icons.double_arrow,
                    size: 48,
                ),
            ),
        ),
        road: Road(
                startIcon: MarkerIcon(
                  icon: Icon(
                    Icons.person,
                    size: 64,
                    color: Colors.brown,
                  ),
                ),
                roadColor: Colors.yellowAccent,
        ),
        markerOption: MarkerOption(
            defaultMarker: MarkerIcon(
                icon: Icon(
                  Icons.person_pin_circle,
                  color: Colors.blue,
                  size: 56,
                  ),
                )
        ),
    );

MapController

Declare MapController to control OSM map

1) Initialisation

 MapController controller = MapController(
                            initMapWithUserPosition: false,
                            initPosition: GeoPoint(latitude: 47.4358055, longitude: 8.4737324),
                            areaLimit: BoundingBox( east: 10.4922941, north: 47.8084648, south: 45.817995, west: 5.9559113,),
                       );

2) Dispose

     controller.dispose();

3) Properties of MapController

Properties Description
initMapWithUserPosition (bool) initialize map with user position (default:true
initPosition (GeoPoint) if it isn't null, the map will be pointed at this position
areaLimit (Bounding) set area limit of the map (default BoundingBox.world())

4) Set map on user current position

 await controller.currentPosition();

5) Zoom IN

 await controller.setZoom(stepZoom: 2);
 // or 
 await controller.zoomIn();

5.1) Zoom Out

 await controller.setZoom(stepZoom: -2);
 // or 
 await controller.zoomOut();
 

5.2) change zoom level

zoomLevel should be between minZoomLevel and maxZoomLevel

 await controller.setZoom(zoomLevel: 8);

6) get current zoom level b>

await controller.getZoom();

7) BoundingBox

set bounding box in the map

await controller.limitAreaMap(BoundingBox( east: 10.4922941, north: 47.8084648, south: 45.817995, west: 5.9559113,));

remove bounding box in the map

await controller.removeLimitAreaMap();

8) Track user current position

for iOS,you should add those line in your info.plist file

   
   
    NSLocationWhenInUseUsageDescription
   
	
   
    any text you want
   
	
   
    NSLocationAlwaysUsageDescription
   
	
   
    any text you want
   
 await controller.enableTracking();

9) Disable tracking user position

 await controller.disabledTracking();

10) update the location

this method will create marker on that specific position

 await controller.changeLocation(GeoPoint(latitude: 47.35387, longitude: 8.43609));

Change the location without create marker

 await controller.goToLocation(GeoPoint(latitude: 47.35387, longitude: 8.43609));

11) recuperation current position

 GeoPoint geoPoint = await controller.myLocation();

12) get center map b>

GeoPoint centerMap = await controller.centerMap;

13) get bounding box map b>

BoundingBox bounds = await controller.bounds;

14) select/create new position

  • we have 2 way to select location in map

14.1 Manual selection (deprecated)

a) select without change default marker

 GeoPoint geoPoint = await controller.selectPosition();

b) select position with dynamic marker

  • Flutter widget
 GeoPoint geoPoint = await controller.selectPosition(
     icon: MarkerIcon(
                      icon: Icon(
                        Icons.location_history,
                        color: Colors.amber,
                        size: 48,
          ), 
);
  • image from network
 GeoPoint geoPoint = await controller.selectPosition(  
         imageURL: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/1.png"
);

c) select using listener from controller directly

  • for more example see home_example.dart c.1) single tap listener
controller.listenerMapSingleTapping.addListener(() {
      if (controller.listenerMapSingleTapping.value != null) {
        /// put you logic here
      }
    });

c.2) long tap listener

controller.listenerMapLongTapping.addListener(() {
      if (controller.listenerMapLongTapping.value != null) {
        /// put you logic here
      }
    });

c.3) region change listener

controller.listenerRegionIsChanging.addListener(() {
      if (controller.listenerRegionIsChanging.value != null) {
        /// put you logic here
      }
    });

14.2 Assisted selection (for more details see example)

 /// To Start assisted Selection
 await controller.advancedPositionPicker();
 /// To get location desired
  GeoPoint p = await controller.getCurrentPositionAdvancedPositionPicker();
  /// To get location desired and close picker
 GeoPoint p = await controller.selectAdvancedPositionPicker();
 /// To cancel assisted Selection
 await controller.cancelAdvancedPositionPicker();

15) Create Marker Programmatically

you can change marker icon by using attribute markerIcon

await controller.addMarker(GeoPoint,markerIcon:MarkerIcon,angle:pi/3);

15.1) Remove marker

 await controller.removeMarker(geoPoint);
  • PS : static position cannot be removed by this method

16) Draw road,recuperate distance in km and duration in sec

you can add an middle position to pass your route through them change configuration of the road in runtime zoom into the region of the road change the type of the road that user want to use

 RoadInfo roadInfo = await controller.drawRoad( 
   GeoPoint(latitude: 47.35387, longitude: 8.43609),
   GeoPoint(latitude: 47.4371, longitude: 8.6136),
   roadType: RoadType.car,
   intersectPoint : [ GeoPoint(latitude: 47.4361, longitude: 8.6156), GeoPoint(latitude: 47.4481, longitude: 8.6266)]
   roadOption: RoadOption(
       roadWidth: 10,
       roadColor: Colors.blue,
       showMarkerOfPOI: false,
       zoomInto: true,
   ),
);
 print("${roadInfo.distance}km");
 print("${roadInfo.duration}sec");

properties of RoadOption

Properties Description
roadColor (Color?) change the default color of the route in runtime
roadWidth (int?) change the road width
showMarkerOfPOI (bool) change the visibility of the markers of the POI (default:false)
zoomInto (bool) change zoom level to make the all the road visible (default:true)

16.b) draw road manually

await controller.drawRoadManually(
        waysPoint,
        Colors.purpleAccent,
        6.0,
      )

17) Delete last road

 await controller.removeLastRoad();

18) Change static GeoPoint position

add new staticPoints with empty list of geoPoints (notice: if you add static point without marker,they will get default maker used by plugin)

change their position over time

change orientation of the static GeoPoint with GeoPointWithOrientation

 await controller.setStaticPosition(List<GeoPoint> geoPoints,String id );

19) Change/Add Marker old/new static GeoPoint position

add marker of new static point

change their marker of existing static geoPoint over time

 await controller.setMarkerOfStaticPoint(String id,MarkerIcon markerIcon );

20) change orientation of the map

 await controller.rotateMapCamera(degree);

21) Draw Shape in the map

  • Circle
 /// to draw
 await controller.drawCircle(CircleOSM(
              key: "circle0",
              centerPoint: GeoPoint(latitude: 47.4333594, longitude: 8.4680184),
              radius: 1200.0,
              color: Colors.red,
              strokeWidth: 0.3,
            ));
 /// to remove Circle using Key
 await controller.removeCircle("circle0");

 /// to remove All Circle in the map 
 await controller.removeAllCircle();
  • Rect
 /// to draw
 await controller.drawRect(RectOSM(
              key: "rect",
              centerPoint: GeoPoint(latitude: 47.4333594, longitude: 8.4680184),
              distance: 1200.0,
              color: Colors.red,
              strokeWidth: 0.3,
            ));
 /// to remove Rect using Key
 await controller.removeRect("rect");

 /// to remove All Rect in the map 
 await controller.removeAllRect();
  • remove all shapes in the map
 await controller.removeAllShapes();

Interfaces:

  • OSMMixinObserver :

contain listener methods to get event from native map view like when mapIsReady,mapRestored

you should add ths line controller.addObserver(this); in initState

override mapIsReady to implement your own logic after initialisation of the map

mapIsReady will replace listenerMapIsReady

Methods Description
mapIsReady (callback) should be override this method, to get notified when map is ready to go or not,
mapRestored (callback) should be override this method, to get notified when map is restored you can also add you bakcup

** example

class YourOwnStateWidget extends State<YourWidget> with OSMMixinObserver {

   //etc
  @override
  void initState() {
    super.initState();
    controller.addObserver(this);
  }
    @override
    Future<void> mapIsReady(bool isReady) async {
      if (isReady) {
        /// put you logic
      }
    }
  @override
  Future<void> mapRestored() async {
    super.mapRestored();
    /// TODO
  }
    //etc
}

OSMFlutter

Properties Description
mapIsLoading (Widget) show custom widget when the map finish initialization
trackMyPosition enable tracking user position.
showZoomController show default zoom controller.
userLocationMarker change user marker or direction marker icon in tracking location
markerOption configure marker of osm map
stepZoom set step zoom to use in zoomIn()/zoomOut() (default 1)
initZoom set init zoom level in the map (default 10)
maxZoomLevel set maximum zoom level in the map (2 <= x <= 19)
minZoomLevel set minimum zoom level in the map (2 <= x <= 19 )
road set color and start/end/middle markers in road
staticPoints List of Markers you want to show always ,should every marker have unique id
onGeoPointClicked (callback) listener triggered when marker is clicked ,return current geoPoint of the marker
onLocationChanged (callback) it is fired when you activate tracking and user position has been changed
onMapIsReady (callback) listener trigger to get map is initialized or not
showDefaultInfoWindow (bool) enable/disable default infoWindow of marker (default = false)
isPicker (bool) enable advanced picker from init of the map (default = false)
showContributorBadgeForOSM (bool) enable to show copyright widget of osm in the map
androidHotReloadSupport (bool) enable to restart osm map in android to support hotReload, default: false

Custom Controller

To create your own MapController to need to extends from BaseMapController, if you want to make a custom initialization to need to call init() and put your code after super.init()

  • example
class CustomMapController extends BaseMapController {

  @override
  void dispose() {
    /// TODO put you logic here
    super.dispose();
  }

  @override
  void init() {
    super.init();
    /// TODO put you logic here
  }
}

STATIC METHODS:

1) Calculate distance between 2 geoPoint position

 double distanceEnMetres = await distance2point(GeoPoint(longitude: 36.84612143139903,latitude: 11.099388684927824,),
        GeoPoint( longitude: 36.8388023164018, latitude: 11.096959785428027, ),);

2) Get search Suggestion of text

you should know that i'm using public api, don't make lot of request

    List<SearchInfo> suggestions = await addressSuggestion("address");

show dialog picker

simple dialog location picker to selected user location

GeoPoint p = await showSimplePickerLocation(
                      context: context,
                      isDismissible: true,
                      title: "Title dialog",
                      textConfirmPicker: "pick",
                      initCurrentUserPosition: true,
                    )

CustomLocationPicker

customizable widget to build search location

you should use PickerMapController as controller for the widget see example : search widget

Properties of CustomLocationPicker

Properties Description
controller (PickerMapController) controller of the widget
appBarPicker (AppBar) appbar for the widget
topWidgetPicker (Widget?) widget will be show on top of osm map,for example to show address suggestion
bottomWidgetPicker (Widget?) widget will be show at bottom of screen for example to show more details about selected location or more action

NOTICE:

For now the map working only for android,iOS will be available soon

If you get ssl certfiction exception,use can use http by following instruction below

If you want to use http in Android PIE or above :

  • enable useSecureURL and add android:usesCleartextTraffic="true" in your manifest like example below :

if you faced build error in fresh project you need to follow those instruction #40

1) remove flutter_osm_plugin from pubspec, after that pub get
2) open android module in android studio ( right click in name of project -> flutter-> open android module in android studio)
3) update gradle version to 4.1.1 ( IDE will show popup to make update)
4) update kotlin version to 1.4.21 & re-build the project
5) re-add flutter_osm_plugin in pubspec , pub get ( or flutter clean & pub get )

Before you publish your application using this library, you should take care about copyright of openStreetMap Data, that's why i add CopyrightOSMWidget see example and this issue #101

MIT LICENCE

Comments
  • Route optimization functionality

    Route optimization functionality

    Hey man, I came across the need to have a route planner, because I have several intersection points drawn on the map, but none of these points has an optimized route, is there something already implemented in your package that displays an optimized route? Or if it doesn't exist, would you implement it? In case it is of any help, there is this service that does this optimization: http://project-osrm.org/docs/v5.24.0/api/#trip-service

    opened by renehw 52
  • Strange behavior on iOS

    Strange behavior on iOS

    Hello, Some strange behavior on iOS. In my App, the map needs to be redrawn with a list of updated markers (triggered by Provider/Consumer principle). To do that, I have wrapped OSMFlutter() into a FutureBuilder(): FutureBuilder( future: _initMap(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { return OSMFlutter(...)

    with: Future _initMap() async { controller.dispose(); controller = await CustomController(initMapWithUserPosition: true); controller.addObserver(this); }

    It works fine on iOs simulators, on Android real device but not on iOs real device: right after the App is launched, I get the right map but markers do not respond to click. After the map has been refreshed, I get a black map with the markers. So, this time no map but the markers respond to click. Another refresh draw correctly the map but the markers are not correctly displayed (only white area). It is obvious that the map initialization mechanism is faulty, maybe my _initMap() is not correct. Could you please help ?

    enhancement 
    opened by Alisofin 49
  • Issue with Map crashing and flickering

    Issue with Map crashing and flickering

    Hi! I have removed all setState and nestedsetState, I am using the provider package to manage my states, However, if there are some changes in the app the whole app will crash. It was okay with the previous version. Some people are also running thru the problems that I am facing so I created a small project to show you the issues. please take a look.

    The steps I where the bug occurs

    1. Run the app wait for the location to load
    2. Go to the search screen 'pick your locationand pick yourdrop off` address
    3. return, the app crashes.

    Also, there is some performance issue like flickering and crashing when navigating to different classes and back. I did all I could for weeks but I just don't understand how to fix it. https://github.com/jesussmile/osm_bug_tracker

    bug 
    opened by jesussmile 32
  • Error with gradle while compiling with version 0.20.0+2

    Error with gradle while compiling with version 0.20.0+2

    When using version 0.20.0+2 of osm_flutter I get an error while compiling.

    Launching lib/main.dart on sdk gphone x86 arm in debug mode...
    Running Gradle task 'assembleDebug'...
    ../../.pub-cache/hosted/pub.dartlang.org/flutter_osm_plugin-0.20.0+2/lib/src/controller/osm/osm_controller.dart:37:22: Error: Too few positional arguments: 1 required, 0 given.
        osmPlatform.close();
    
    bug 
    opened by cbopp-art 29
  • Black screen (logs: `payment required`)

    Black screen (logs: `payment required`)

    Thanks for the library. I built a free compass app really quickly. I would like to release it for free.

    However, when running the library on iOS, I got a black map.

    flutter: Map is ready: false # my own logs
    ERROR importer.cpp:63: Unable to retrieve 'https://firebasestorage.googleapis.com/v0/b/osm-resources.appspot.com/o/osm-style.zip?alt=media&token=30e0c9fe-af0b-4994-8a73-2d31057014d4': payment required
    WARNING sceneLoader.cpp:607: No source defined in the yaml scene configuration.
    flutter: Map is ready: true # my own logs
    

    There are 2 notable things:

    • log: payment required
    • When visiting that firebase storage link, I get a 402 error: Quota has been exceeded for this project. Please visit the Firebase pricing page to learn more.

    What do you suggest we do when we hit these rate limits?

    bug Platform:iOS 
    opened by ben-xD 27
  • Feature request to change the orientation of marker

    Feature request to change the orientation of marker

    With the current option to add marker I can't find a way to change the orientation of MarkerIcon, So, all objects on the map will face the same direction, With the Location plugin it is possible to get the heading of the object, is it possible to change the rotation based on heading? Something like this?

     markerIcon: MarkerIcon(
                rotation: currentLocation.heading
                image: AssetImage(
                  "images/images/jogger.png",
                ),
              ));
    
    enhancement 
    opened by jesussmile 24
  • Markers dissappear when zoom out

    Markers dissappear when zoom out

    Hello. I am viewing 3 static positions via mapIsRead function:

    // Call method mapIsReady when map is initialiazed
      @override
      Future<void> mapIsReady(bool isReady) async {
        // Retrieve data from db
        // If the map is initialized, then ...
        if (isReady) {
          // Set the bounding box from shared preferences to a variable 'currentBoundingBox'
          await controller.zoomToBoundingBox(currentBoundingBox, paddinInPixel: 0);
          // Add a marker programatically
          await controller.setStaticPosition(_staticPositionsList, 'Markers');
        }
      }
    
    The  _staticPositionsList is the list of static Positions I am getting from firebase real time dB and fetch it once with ".get()" call.
    
    Here is the code:
    
    void _performSingleFetch() {
        _database.child('events').get().then((value) {
          final geoPointsList = <GeoPoint>[];
          final allEvents = Map<String, dynamic>.from(value.value as Map);
          geoPointsList.addAll(allEvents.values.map((e) {
            final singleEvent = EventModel.fromRTDB(Map<String, dynamic>.from(e));
            return GeoPoint(
                latitude: singleEvent.latitude, longitude: singleEvent.longitude);
          }));
          setState(() {
            _staticPositionsList = geoPointsList;
          });
        });
      }
    
    
    

    When I try to put a stream instead of a one time fetch and when I change the latitude and longitude of a geopoint via firebase, that streams calles and then the map rebuilds but the static positions stay where they been.

    So, I have two questions.

    First, how to deal with changing the static positions real time and the second. Why the markers dissappear when zoom out from some zoom like in the pictures below

    Screenshot_20220726_103541_com wedowedo osmwedo creenshot_20220726_103535_com wedowedo osmwedo Screenshot_20220726_103523_com wedowedo osmwedo bug 
    opened by blablabla123-cell 23
  • App close in release mode

    App close in release mode

    when we search for address with the search bar to pick an address in CustomPickerLocation and go back to main home map the application crash (map freeze 1s) and close (only in release mode)

    opened by h1amza 23
  • map can't move only zoom in or zoom out

    map can't move only zoom in or zoom out

    i have 2 app using osm (client and driver) in driver it's fine but in client app the map don't move(right left up down) Both of them have the same code:

    Scaffold( key: controller.drawerKey, endDrawer: const SideMenuView(), resizeToAvoidBottomInset: false, backgroundColor: Colors.white, body: OSMFlutter( controller: controller.mapController, trackMyPosition: true, androidHotReloadSupport: true, initZoom: 17, maxZoomLevel: 19, ), );

    opened by h1amza 22
  • null object reference

    null object reference

    This generally occurs when running it thru an IDE, either to debug or running without debugging. Null Object Reference Impact: The Map doesn't load, Could you please check it

    Debug Console

    [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: PlatformException(error, Attempt to invoke virtual method 'org.osmdroid.views.MapViewRepository org.osmdroid.views.MapView.getRepository()' on a null object reference, null, java.lang.NullPointerException: Attempt to invoke virtual method 'org.osmdroid.views.MapViewRepository org.osmdroid.views.MapView.getRepository()' on a null object reference
    

    Files causing the error

    
    E/flutter (28434): )
    E/flutter (28434): #0      StandardMethodCodec.decodeEnvelope
    package:flutter/…/services/message_codecs.dart:581
    E/flutter (28434): #1      MethodChannel._invokeMethod
    package:flutter/…/services/platform_channel.dart:158
    E/flutter (28434): <asynchronous suspension>
    E/flutter (28434): #2      MethodChannelOSM.addPosition
    package:flutter_osm_plugin/…/channel/osm_method_channel.dart:156
    E/flutter (28434): <asynchronous suspension>
    E/flutter (28434): #3      OSMController.changeLocation
    package:flutter_osm_plugin/…/controller/osm_controller.dart:169
    E/flutter (28434): <asynchronous suspension>
    E/flutter (28434): #4      OSMController.initMap
    package:flutter_osm_plugin/…/controller/osm_controller.dart:93
    E/flutter (28434): <asynchronous suspension>
    E/flutter (28434): #5      BaseMapController.init.<anonymous closure>
    package:flutter_osm_plugin/…/controller/base_map_controller.dart:39
    E/flutter (28434): <asynchronous suspension>
    
    opened by jesussmile 22
  • OSM map reloads in tab view

    OSM map reloads in tab view

    Hi, I am using a BottomNavigationBar with 4 tabs, As I move on from other tabs and come back to HomeTabPage OSM Flutter map will reload Earlier in previous versions, I would use AutomaticKeepAliveClientMixin and it works fine but now with the recent update the reloading causes reload and I lose a lot of functionality like tracking vehicles, etc. Here is a stripped-down version of the code, How can I fix this?

    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
      Widget build(BuildContext context) {
        return MaterialApp(
            title: 'Flutter Demo',
            theme: ThemeData(
              primarySwatch: Colors.blue,
            ),
            home: MainScreen()
      }
    }
    

    The MainScreen

    import 'package:drivers_app/tabPages/earnings_tab_page.dart';
    import 'package:drivers_app/tabPages/home_tab_page.dart';
    
    import 'package:drivers_app/tabPages/profile_tab_page.dart';
    import 'package:drivers_app/tabPages/rating_tab_page.dart';
    import 'package:flutter/material.dart';
    
    class MainScreen extends StatefulWidget {
      //const MainScreen({ Key? key }) : super(key: key);
      static const String idScreen = "mainScreen";
    
      @override
      _MainScreenState createState() => _MainScreenState();
    }
    
    class _MainScreenState extends State<MainScreen>
        with SingleTickerProviderStateMixin {
      TabController tabController;
      int selectedIndex = 0;
      void onItemClicked(int index) {
        setState(() {
          selectedIndex = index;
          tabController.index = selectedIndex;
        });
      }
    
      @override
      void initState() {
        super.initState();
        tabController = TabController(length: 4, vsync: this);
      }
    
      @override
      void dispose() {
        super.dispose();
        tabController.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: TabBarView(
            physics: NeverScrollableScrollPhysics(),
            controller: tabController,
            children: [
              HomeTabPage(),
              EarningTabPage(),
              RatingTabPage(),
              ProfileTabPage(),
            ],
          ),
          bottomNavigationBar: BottomNavigationBar(
            items: [
              BottomNavigationBarItem(icon: Icon(Icons.home), label: "Home"),
              BottomNavigationBarItem(
                  icon: Icon(Icons.credit_card), label: "Earnings"),
              BottomNavigationBarItem(icon: Icon(Icons.star), label: "Ratings"),
              BottomNavigationBarItem(icon: Icon(Icons.person), label: "Account"),
            ],
            unselectedItemColor: Colors.black54,
            selectedItemColor: Colors.yellow,
            type: BottomNavigationBarType.fixed,
            selectedLabelStyle: TextStyle(fontSize: 12.0),
            showUnselectedLabels: true,
            currentIndex: selectedIndex,
            onTap: onItemClicked,
          ),
        );
      }
    }
    

    This is the HomeTabPage

    import 'package:drivers_app/configMaps.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter_osm_plugin/flutter_osm_plugin.dart';
    import 'package:geolocator/geolocator.dart';
    
    class HomeTabPage extends StatefulWidget {
      const HomeTabPage({Key key}) : super(key: key);
    
      @override
      _HomeTabPageState createState() => _HomeTabPageState();
    }
    
    class _HomeTabPageState extends State<HomeTabPage>
        with AutomaticKeepAliveClientMixin, OSMMixinObserver {
      @override
      bool get wantKeepAlive => true;
      Position initPositionPoint;
      GeoPoint initPosition;
    
      @override
      void initState() {
        super.initState();
    
        osmController = MapController(initMapWithUserPosition: true);
      }
    
      @override
      Future<void> mapIsReady(bool isReady) async {
        if (isReady) {
          await osmController.rotateMapCamera(45.0);
          await osmController.currentLocation();
          await osmController.rotateMapCamera(0);
          locatePosition();
        }
      }
    
      void locatePosition() async {
        initPositionPoint = await Geolocator.getCurrentPosition(
            desiredAccuracy: LocationAccuracy.high);
        print("This is your Position:: " + initPositionPoint.toString());
    
        GeoPoint initPos = GeoPoint(
            latitude: initPositionPoint.latitude,
            longitude: initPositionPoint.longitude);
        initPosition = initPos;
        currentPosition = initPos;
      }
    
      MapController osmController;
      final GlobalKey _mapKey = GlobalKey();
      @override
      Widget build(BuildContext context) {
        return Stack(children: [
          OSMFlutter(
            key: _mapKey,
            controller: osmController,
            trackMyPosition: true,
            initZoom: 18,
            minZoomLevel: 8,
            maxZoomLevel: 18,
            stepZoom: 1.0,
            userLocationMarker: UserLocationMaker(
              personMarker: MarkerIcon(
                image: AssetImage("images/images/car-ios.png"),
              ),
              directionArrowMarker: MarkerIcon(
                image: AssetImage("images/images/car-ios.png"),
              ),
            ),
            road: Road(
              startIcon: MarkerIcon(
                icon: Icon(
                  Icons.person,
                  size: 64,
                  color: Colors.brown,
                ),
              ),
              roadColor: Colors.yellowAccent,
            ),
            markerOption: MarkerOption(
                defaultMarker: MarkerIcon(
              icon: Icon(
                Icons.star_half_rounded,
                color: Colors.blue,
                size: 56,
              ),
            )),
          )
        ]);
      }
    }
    
    opened by jesussmile 21
  • Text in marker

    Text in marker

    Hello! Thanks for your plugin There is some problem. I'm using version ^0.50.0-alpha.4, since the stable version won't start for me, for this reason: uint8list pngbytes = bytedata.buffer.asuint8list();

    But since ^0.50.0-alpha.4 works there are some difficulties. In my design, on the placemark marker, in addition to the icon, there is also text. If I leave only one icon (it is in the form of an iconWidget), then everything is fine. If I put more text, then everything blurs (I attach a screen). And even if I leave one text, everything also blurs. I understand that this is connected by a width limit. Can this somehow be corrected?

    here's code:

    OSMFlutter(
                controller: mapController,
                trackMyPosition: true,
                androidHotReloadSupport: true,
                initZoom: 14,
                minZoomLevel: 3,
                maxZoomLevel: 19,
                stepZoom: 1.0,
                userLocationMarker: UserLocationMaker(
                  personMarker: const MarkerIcon(
                    icon: Icon(
                      Icons.location_history_rounded,
                      color: Colors.red,
                      size: 48,
                    ),
                  ),
                  directionArrowMarker: const MarkerIcon(
                    icon: Icon(
                      Icons.double_arrow,
                      size: 48,
                    ),
                  ),
                ),
                markerOption: MarkerOption(
                  defaultMarker: const MarkerIcon(
                    icon: Icon(
                      Icons.person_pin_circle,
                      color: Colors.blue,
                      size: 56,
                    ),
                  ),
                ),
                onGeoPointClicked: (geoPoint) async {
                },
                staticPoints: points
              ),
    

    here's marker widget code:

    class MarkerIconPoint extends StatelessWidget{
    
      final String pointName;
    
      const MarkerIconPoint({Key? key, required this.pointName}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Assets.images.mapPoint.svg(
            height: 40.h, width: 40.w
        );
      }
    
    }
    

    here's a blurry:

    imgonline-com-ua-Resize-zrgOIowKbH2

    here's a normal:

    imgonline-com-ua-Resize-uEvd9TMHP3SmkV

    opened by MaximVod 2
  • Clusterization and osm hook plugin connection failed

    Clusterization and osm hook plugin connection failed

    I would like to thank the developers for your package.

    I just have a couple of questions. 1 osm_hook plugin conflicts with new osm_flutter 0.42.0 have to use old versions of osm_flutter 2 I understand that the package does not provide a marker clustering function?

    Thank you so much. Victory for Ukraine

    opened by Soliardi-Chyngyz 2
  • Add custom information to GeoPoint marker

    Add custom information to GeoPoint marker

    Hello,

    I am currently trying to add information to my marker (description, tags, ..) that I can fetch when clicking the marker. My problem is that onGeoPointClicked returns a GeoPoint object and doesn't allow it to have more into rather than the latitude and longitude. Is there a way to override the callback onGeoPointClicked to have a CustomGeoPoint object ?

    Thank you in advance !

    opened by JaimeCosteira 4
  • Draw shapes on iOS

    Draw shapes on iOS

    Hi @liodali,

    Are you considering working on draw shapes on iOS? If yes, when it will be available? if not, do you have an approach to work in this behavior? I can help with that.

    BR.

    opened by isaacfi 1
  • Bug: rotation is opposite on Android and iOS

    Bug: rotation is opposite on Android and iOS

    When we ask osm_flutter to rotate by 90 degrees,

    • On Android, it rotates clockwise
    • On iOS, it rotates anti-clockwise

    If we rotate the camera by -90 degrees (90 degrees clockwise), this is equivalent to the map rotating the opposite way, 90 degrees (90 degrees anticlockwise).

    Because the API on osm_flutter says "rotate_map", on iOS we should invert the rotation, because the API does mapView.setCameraPosition.

        private func rotateMap(call: FlutterMethodCall) {
            let angle = call.arguments as! Double
            if (angle > 0.0) {
                mapView.setCameraPosition(TGCameraPosition(center: mapView.position, zoom: mapView.zoom, bearing: CLLocationDirection(CGFloat(angle)), pitch: 0.0), withDuration: 0.2, easeType: TGEaseType.sine)
            }
        }
    

    On Android, the API rotates the map:

    from [docs](https://osmdroid.github.io/osmdroid/javadocAll/org/osmdroid/views/MapController.html)

    Start animating the map towards the given point.

        private fun mapOrientation(call: MethodCall, result: MethodChannel.Result) {
            //map!!.mapOrientation = (call.arguments as Double?)?.toFloat() ?: 0f
            // Convert rotation into orientation
            val orientation = (call.arguments as Double?)?.toFloat() ?: 0f
            map!!.controller.animateTo(
                    map!!.mapCenter,
                    map!!.zoomLevelDouble,
                    null,
                    orientation
            )
            mapSnapShot().saveMapOrientation(map!!.mapOrientation)
            map!!.invalidate()
            result.success(null)
        }
    

    TLDR: RotateMap != Rotate camera


    Side note: Mapbox doesn't have map rotation API, but camera rotation.


    My workaround

    It's pretty easy to fix this on my end, but I think it would be good to fix this for everyone.

          if (Platform.isIOS) {
            final rotationCompensation = -yaw;
            final positiveOnlyRotationCorrection = (rotationCompensation < 0)
                ? rotationCompensation + 360
                : rotationCompensation;
            mapController.rotateMapCamera(positiveOnlyRotationCorrection);
          } else if (Platform.isAndroid) {
            final rotationCompensation = yaw;
            // OSM on Android rotates the **wrong way.** I will make an PR for this.
            mapController.rotateMapCamera(rotationCompensation);
          }
    

    Side note, I got the error with the example app, so I just had to update the deployment target to be the same for debug, release and profile in Xcode:

    RuntimeError - [Xcodeproj] Consistency issue: build setting `IPHONEOS_DEPLOYMENT_TARGET` has multiple
        values: `{"Debug"=>"11.0", "Release"=>"11.0", "Profile"=>"13.0"}`
    
    opened by ben-xD 2
Owner
hamza mohamed ali
Android & Flutter developer
hamza mohamed ali
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 plugin for Google Maps

IMPORTANT: This plugin is no longer under development Why? We initially built this plugin to fill an early gap in flutter. Since then, Google has made

AppTree Software, Inc 415 Dec 29, 2022
Flutter plugin for forward and reverse geocoding

geocoder Forward and reverse geocoding. Usage Import package:geocoder/geocoder.dart, and use the Geocoder.local to access geocoding services provided

Aloïs Deniel 177 Dec 31, 2022
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
Flutter geolocation plugin for Android and iOS.

geolocation Flutter geolocation plugin for Android API 16+ and iOS 9+. Features: Manual and automatic location permission management Current one-shot

Loup 222 Jan 2, 2023
Apple Maps Plugin for Flutter

apple_maps_flutter A Flutter plugin that provides an Apple Maps widget. The plugin relies on Flutter's mechanism for embedding Android and iOS views.

Luis Thein 50 Dec 31, 2022
Flutter plugin for launching maps

Map Launcher Map Launcher is a flutter plugin to find available maps installed on a device and launch them with a marker or show directions. Marker Na

Alex Miller 189 Dec 20, 2022
Android and iOS Geolocation plugin for Flutter

Flutter geolocator plugin The Flutter geolocator plugin is build following the federated plugin architecture. A detailed explanation of the federated

Baseflow 1k Jan 5, 2023
Android and iOS Geolocation plugin for Flutter

Flutter geolocator plugin The Flutter geolocator plugin is build following the federated plugin architecture. A detailed explanation of the federated

Baseflow 891 Nov 14, 2021
A Flutter plugin to easily handle realtime location in iOS and Android. Provides settings for optimizing performance or battery.

Flutter Location Plugin This plugin for Flutter handles getting a location on Android and iOS. It also provides callbacks when the location is changed

Guillaume Bernos 953 Dec 22, 2022
Android and iOS Geolocation plugin for Flutter

Flutter geolocator plugin The Flutter geolocator plugin is build following the federated plugin architecture. A detailed explanation of the federated

Baseflow 1k Dec 27, 2022
A Flutter plugin for appodeal

flutter_appodeal A Flutter plugin for iOS and Android to use Appodeal SDK in your apps Getting Started For help getting started with Flutter, view our

null 14 Feb 19, 2022
A Flutter plugin for integrating Google Maps in iOS, Android and Web applications

flutter_google_maps A Flutter plugin for integrating Google Maps in iOS, Android and Web applications. It is a wrapper of google_maps_flutter for Mobi

MarchDev Toolkit 86 Sep 26, 2022
A flutter plugin that's decodes encoded google poly line string into list of geo-coordinates suitable for showing route/polyline on maps

flutter_polyline_points A flutter plugin that decodes encoded google polyline string into list of geo-coordinates suitable for showing route/polyline

Adeyemo Adedamola 75 Oct 25, 2022
A Flutter plugin which provides 'Picking Place' using Google Maps widget

Google Maps Places Picker Refractored This is a forked version of google_maps_place_picker package, with added custom styling and features.

Varun 5 Nov 13, 2022
A plugin that offers widgets for Wear OS by Google

Flutter Wear Plugin A plugin that offers Flutter support for Wear OS by Google (Android Wear). To use this plugin you must set your minSdkVersion to 2

Flutter Community 114 Dec 18, 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
flutter_map plugin to request and display the users location and heading on the map

The plugin is discontinued. Feel free to fork it or checkout similar plugins. Flutter Map – Location plugin A flutter_map plugin to request and displa

Fabian Rosenthal 19 Oct 11, 2022
Flutter_map plugin to display geojson, vector tiles, clusters using sliced vectors

geojson_vector_slicer A flutter_map plugin to display fast geojson by slicing into tiles. Slicing based off https://github.com/mapbox/geojson-vt IMPOR

Ian 4 Oct 18, 2022