Search code examples
flutterdartlocationmapbox

How to get user's location in flutter's official mapbox package?


I'm using the package mapbox_maps_flutter 0.4.0. And I can't find a way to get the user's current location coordinates.

I can only update LocationComponentSettings that don't have coordinates. I'd like to have a method getUserLocation() or getLastKnownLocation().


Solution

  • I found a way:

    Position? userLocation = await mapboxMap?.style.getPuckPosition();
    
    if (userLocation != null) {
       print('Location: ${userLocation}');
    }
    
    extension PuckPosition on StyleManager {
      Future<Position> getPuckPosition() async {
        Layer? layer;
        if (Platform.isAndroid) {
          layer = await getLayer("mapbox-location-indicator-layer");
        } else {
          layer = await getLayer("puck");
        }
        final location = (layer as LocationIndicatorLayer).location;
        return Future.value(Position(location![1]!, location[0]!));
      }
    }
    

    Then userLocation has Position? type (see package turf). However, you must first enable location tracking:

    mapboxMap?.location.updateSettings(LocationComponentSettings(enabled: true));