Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
How to use Location API in Android to track your current location?
This example demonstrates how do I use Location API in android to track your current location.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Add the following dependency in the build.gradle (Module:app) −
implementation 'com.google.android.gms:play-services-maps:17.0.0'
Step 2 − Add the following code to res/layout/activity_main.xml.
Step 3 − Add the following code to src/MainActivity.java
import androidx.fragment.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback {
GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng myCurrentLocation = new LatLng(13.0827, 80.2707);
mMap.addMarker(new MarkerOptions().position(myCurrentLocation).title("This is My current Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myCurrentLocation));
}
}
Step 4 − Open res/strings.xml and add the following code −
Sample Map AIzaSyC19gZFIlF5OVySzG9iMAeDFzOmUuCHZ5Q
Step 5 − Add the following code to androidManifest.xml
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run
icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

Click here to download the project code.
