Flutter google map live location

Hasnain Mirrani
2 min readApr 29, 2023

To add continuous live changing location on Google Maps in Flutter, you can follow these steps:

  1. First, you need to get the user’s location using the location package. You can add it to your pubspec.yaml file and import it in your Dart file as follows:
  2. import ‘package:location/location.dart’;
  3. Next, you need to initialize the Location object and request for the user's location. You can do this using the following code:
  4. Location location = Location();
  5. // Request for the user’s location
    bool serviceEnabled;
    PermissionStatus permissionStatus;
  6. serviceEnabled = await location.serviceEnabled();
    if (!serviceEnabled) {
    serviceEnabled = await location.requestService();
    if (!serviceEnabled) {
    return;
    }
    }
  7. permissionStatus = await location.hasPermission();
    if (permissionStatus == PermissionStatus.denied) {
    permissionStatus = await location.requestPermission();
    if (permissionStatus != PermissionStatus.granted) {
    return;
    }
    }
  8. // Get the current location
    LocationData currentLocation = await location.getLocation();
  9. Now that you have the user’s current location, you can display it on the map using the google_maps_flutter package. You can add it to your pubspec.yaml file and import it in your Dart file as follows:
  10. import ‘package:google_maps_flutter/google_maps_flutter.dart’;
  11. Next, you can create a GoogleMap widget and pass in the user's current location using the LatLng class. You can also set the myLocationEnabled property to true to display the user's location on the map. Here's an example code:
  12. GoogleMap(
    initialCameraPosition: CameraPosition(
    target: LatLng(currentLocation.latitude, currentLocation.longitude),
    zoom: 15,
    ),
    myLocationEnabled: true,
    ),
  13. To continuously update the user’s location on the map as they move, you can use a StreamBuilder widget and listen to the user's location updates using the onLocationChanged stream from the location package. Here's an example code:
  14. StreamBuilder<LocationData>(
    stream: location.onLocationChanged,
    builder: (BuildContext context, AsyncSnapshot<LocationData> snapshot) {
    if (snapshot.hasData) {
    return GoogleMap(
    initialCameraPosition: CameraPosition(
    target: LatLng(snapshot.data.latitude, snapshot.data.longitude),
    zoom: 15,
    ),
    myLocationEnabled: true,
    );
    } else {
    return CircularProgressIndicator();
    }
    },
    ),
  15. This will continuously update the user’s location on the map as they move. Note that you may need to handle permissions and error scenarios in your code as well.

--

--

Hasnain Mirrani

Update the lattest and well explain All about Flutter make you from Zero to Hero in Flutter. follow https://www.linkedin.com/in/hasnain-mirrani-b47ab7131