zoom in/out not possible: always focus on my position flutter

867

You can try this
Declare a variable that hold you position as your location changes

Map _position;

The in your location change listener

_locationSubscription = _locationTracker.onLocationChanged().listen((newLocalData) {
  setState(() {
    _position = {
      "lat": newLocalData.latitude,
      "lng": newLocalData.longitude,
      "heading": newLocalData.heading,
    };
  });
  if (_controller != null) updateMarkerAndCircle(newLocalData, imageData);
});

Finally, call this method each time you want to center the map to your current position

void _gotoCurrentPosition() {
    if (null != _controller && null != _position) {
      _controller.animateCamera(CameraUpdate.newCameraPosition(new CameraPosition(
         bearing: _position["heading"],
         target: LatLng(_position["lat"], _position["lng"]),
         tilt: 0,
         zoom: 18.00),
       ),);
    }
}
Share:
867
hammadu
Author by

hammadu

Updated on November 21, 2022

Comments

  • hammadu
    hammadu over 1 year

    I just started learning flutter and I am trying to build a mobile app using google maps. I am following a tutorial which is bulding an app that track my position all the time:

    example

    It is working pretty good, the problem is that when ever I try to zoom in/out it take me back to my position with the default zoom even if I am not mooving.

    I am trying to be able to zoom in/out even if i am moving and tak me back my position only when i click on button.

    here is the source code:

    import 'dart:typed_data';
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'package:google_maps_flutter/google_maps_flutter.dart';
    import 'package:location/location.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'Flutter Maps',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(title: 'Flutter Map Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      StreamSubscription _locationSubscription;
      Location _locationTracker = Location();
      Marker marker;
      Circle circle;
      GoogleMapController _controller;
    
      static final CameraPosition initialLocation = CameraPosition(
        target: LatLng(37.42796133580664, -122.085749655962),
        zoom: 14.4746,
      );
    
      Future<Uint8List> getMarker() async {
        ByteData byteData = await DefaultAssetBundle.of(context).load("assets/car_icon.png");
        return byteData.buffer.asUint8List();
      }
    
      void updateMarkerAndCircle(LocationData newLocalData, Uint8List imageData) {
        LatLng latlng = LatLng(newLocalData.latitude, newLocalData.longitude);
        this.setState(() {
          marker = Marker(
              markerId: MarkerId("home"),
              position: latlng,
              rotation: newLocalData.heading,
              draggable: false,
              zIndex: 2,
              flat: true,
              anchor: Offset(0.5, 0.5),
              icon: BitmapDescriptor.fromBytes(imageData));
          circle = Circle(
              circleId: CircleId("car"),
              radius: newLocalData.accuracy,
              zIndex: 1,
              strokeColor: Colors.blue,
              center: latlng,
              fillColor: Colors.blue.withAlpha(70));
        });
      }
    
      void getCurrentLocation() async {
        try {
    
          Uint8List imageData = await getMarker();
          var location = await _locationTracker.getLocation();
    
          updateMarkerAndCircle(location, imageData);
    
          if (_locationSubscription != null) {
            _locationSubscription.cancel();
          }
    
    
          _locationSubscription = _locationTracker.onLocationChanged().listen((newLocalData) {
            if (_controller != null) {
              _controller.animateCamera(CameraUpdate.newCameraPosition(new CameraPosition(
                  bearing: 192.8334901395799,
                  target: LatLng(newLocalData.latitude, newLocalData.longitude),
                  tilt: 0,
                  zoom: 18.00)));
              updateMarkerAndCircle(newLocalData, imageData);
            }
          });
    
        } on PlatformException catch (e) {
          if (e.code == 'PERMISSION_DENIED') {
            debugPrint("Permission Denied");
          }
        }
      }
    
      @override
      void dispose() {
        if (_locationSubscription != null) {
          _locationSubscription.cancel();
        }
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: GoogleMap(
            mapType: MapType.hybrid,
            initialCameraPosition: initialLocation,
            markers: Set.of((marker != null) ? [marker] : []),
            circles: Set.of((circle != null) ? [circle] : []),
            onMapCreated: (GoogleMapController controller) {
              _controller = controller;
            },
    
          ),
          floatingActionButton: FloatingActionButton(
              child: Icon(Icons.location_searching),
              onPressed: () {
                getCurrentLocation();
              }),
        );
      }
    }
    

    Please help me guys! Thanks.

  • hammadu
    hammadu over 3 years
    So what should it be if I want to be able to zoom in/out and only get my position if i click on the button?