Flutter google map live location
2 min readApr 29
--
To add continuous live changing location on Google Maps in Flutter, you can follow these steps:
- 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: - import ‘package:location/location.dart’;
- Next, you need to initialize the
Location
object and request for the user's location. You can do this using the following code: - Location location = Location();
- // Request for the user’s location
bool serviceEnabled;
PermissionStatus permissionStatus; - serviceEnabled = await location.serviceEnabled();
if (!serviceEnabled) {
serviceEnabled = await location.requestService();
if (!serviceEnabled) {
return;
}
} - permissionStatus = await location.hasPermission();
if (permissionStatus == PermissionStatus.denied) {
permissionStatus = await location.requestPermission();
if (permissionStatus != PermissionStatus.granted) {
return;
}
} - // Get the current location
LocationData currentLocation = await location.getLocation(); - 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: - import ‘package:google_maps_flutter/google_maps_flutter.dart’;
- Next, you can create a
GoogleMap
widget and pass in the user's current location using theLatLng
class. You can also set themyLocationEnabled
property totrue
to display the user's location on the map. Here's an example code: - GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(currentLocation.latitude, currentLocation.longitude),
zoom: 15,
),
myLocationEnabled: true,
), - 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 theonLocationChanged
stream from thelocation
package. Here's an example code: - 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();
}
},
), - 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.