How to Get Users Current Location on Google Maps in Flutter?
Last Updated :
25 Nov, 2022
Nowadays Google Maps is one of the popular Applications for navigation or finding any Location. With this, we can find out the current Location of any person. So in this article, we are going to see how to get users' current Location in Flutter.
Step By Step Implementation
Step 1: Create a New Project in Android Studio
To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.
Step 2: Generating API Key for Using Google Maps
Check out the below article on How to generate an API key for using Google Maps. After developing that key we have to use it within our project to integrate Google Maps.
Now, follow the Steps to Implement Google Maps in the Flutter Application
Step 3: Adding Dependency to pubspec.yaml File
dependencies:
flutter:
google_maps_flutter: ^2.1.8
geolocator: ^9.0.2
Now click on pub.get to configure.
Step 4: Update build.gradle File
Navigate to android>app>build.gradle file and update code on the below line.
Change Compile SDK Version
android {
compileSdkVersion 31
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
Change Min SDK Version
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.google_maps"
minSdkVersion 20
targetSdkVersion 30
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
Step 5: Add API Key to Android Manifest File
Navigate to android > app > src > main > AndrodManifest.xml file and add the below code in the manifest tag. Make sure to add your Google Maps API key in the value.
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="Enter your API key here"/>
Step 6: Add the Following Permissions to the Android Manifest File
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
Step 7: Working with main.dart File
Navigate to lib > main.dart file and add the below code to it. Comments are added in the code to get to know in detail.
Dart
import 'package:flutter/material.dart';
import 'package:google_maps/HomePage.dart';
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(
// on below line we are specifying title of our app
title: 'GFG',
// on below line we are hiding debug banner
debugShowCheckedModeBanner: false,
theme: ThemeData(
// on below line we are specifying theme
primarySwatch: Colors.green,
),
// First screen of our app
home: const HomePage(),
);
}
}
Step 7: Creating a new Dart File for Home Page
Navigate to lib > Right click on it > New > Dart File and name it as HomePage.dart. After creating that file add the below code to it. Comments are added in the code to get to know it in detail.
Dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Completer<GoogleMapController> _controller = Completer();
// on below line we have specified camera position
static final CameraPosition _kGoogle = const CameraPosition(
target: LatLng(20.42796133580664, 80.885749655962),
zoom: 14.4746,
);
// on below line we have created the list of markers
final List<Marker> _markers = <Marker>[
Marker(
markerId: MarkerId('1'),
position: LatLng(20.42796133580664, 75.885749655962),
infoWindow: InfoWindow(
title: 'My Position',
)
),
];
// created method for getting user current location
Future<Position> getUserCurrentLocation() async {
await Geolocator.requestPermission().then((value){
}).onError((error, stackTrace) async {
await Geolocator.requestPermission();
print("ERROR"+error.toString());
});
return await Geolocator.getCurrentPosition();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color(0xFF0F9D58),
// on below line we have given title of app
title: Text("GFG"),
),
body: Container(
child: SafeArea(
// on below line creating google maps
child: GoogleMap(
// on below line setting camera position
initialCameraPosition: _kGoogle,
// on below line we are setting markers on the map
markers: Set<Marker>.of(_marker),
// on below line specifying map type.
mapType: MapType.normal,
// on below line setting user location enabled.
myLocationEnabled: true,
// on below line setting compass enabled.
compassEnabled: true,
// on below line specifying controller on map complete.
onMapCreated: (GoogleMapController controller){
_controller.complete(controller);
},
),
),
),
// on pressing floating action button the camera will take to user current location
floatingActionButton: FloatingActionButton(
onPressed: () async{
getUserCurrentLocation().then((value) async {
print(value.latitude.toString() +" "+value.longitude.toString());
// marker added for current users location
_markers.add(
Marker(
markerId: MarkerId("2"),
position: LatLng(value.latitude, value.longitude),
infoWindow: InfoWindow(
title: 'My Current Location',
),
)
);
// specified current users location
CameraPosition cameraPosition = new CameraPosition(
target: LatLng(value.latitude, value.longitude),
zoom: 14,
);
final GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newCameraPosition(cameraPosition));
setState(() {
});
});
},
child: Icon(Icons.local_activity),
),
);
}
}
Output:
Similar Reads
How to Add Custom Markers on Google Maps in Flutter?
Google Maps is one of the popular apps used nowadays for navigation or locating markers on Google Maps. We have seen markers on Google Maps for various locations. But In this article, we are going to see how to implement multiple custom markers on Google Maps in Flutter. Step By Step ImplementationS
4 min read
How to Move Camera to any Position in Google Maps in Flutter?
Google Maps is of the most used application nowadays for navigation. If search for any location our camera on Google Map moves to that position. In this article, we are going to see how to Move the Camera to any Position in Google Maps in Flutter. Step By Step ImplementationStep 1: Create a New Pro
4 min read
How to Implement Current Location Button Feature in Google Maps in Android?
The current location is a feature on Google Maps, that helps us locate the device's position on the Map. Through this article, while we will be implementing Google Maps, we shall also be implementing a button, which will fetch our current location and navigate it on the map. Note that we are going t
5 min read
How to Draw Polygon on Google Maps in Flutter?
Google Maps is used in many Android applications. We can use Polygons to represent routes or areas in Google Maps. So in this article, we are going to see how to Draw Polygon in Google Maps in Flutter. Step By Step ImplementationStep 1: Create a New Project in Android StudioTo set up Flutter Develop
4 min read
How to get user location in Android
Many apps in Android uses user's locations be it for ordering cabs or delivering food and items. Here, a simple android app that would return the user's latitude and longitude is made. Once the latitude and longitude are known, the exact location on Google Maps can be seen using the following query:
6 min read
How to Get Current Location Inside Android Fragment?
A Fragment is a piece of an activity that enables more modular activity design. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts. Android devices exist in a variety of screen sizes and densities. Fragments simplify the reuse of components in different
5 min read
How to Integrate Google Maps in Flutter Applications?
We all have seen that Google Maps is used by many applications such as Ola, Uber, Swiggy, and others. We must set up an API project with the Google Maps Platform in order to integrate Google Maps into our Flutter application. In this article, we will look at How to Integrate Google Maps in Flutter A
4 min read
How to Use Different Types of Google Maps in Android?
When we use the default application of Google Maps we will get to see different types of Maps present inside this application. We will get to see satellite maps, terrain maps, and many more. We have seen adding Google Maps in the Android application. In this article, we will take a look at the imple
4 min read
How to Get Current Location in Android?
As a developer when you work on locations in Android then you always have some doubts about selecting the best and efficient approach for your requirement. So in this article, we are going to discuss how to get the user's current location in Android. There are two ways to get the current location of
5 min read
How to Add Multiple Markers on Google Map in Flutter?
Google Maps is one of the popular apps used nowadays for navigation or locating markers on Google Maps. We have seen markers on Google Maps for various locations. In this article, we are going to see how to implement multiple markers on Google Maps in Flutter. Step By Step ImplementationStep 1: Crea
4 min read