Introduction
Google Maps is a widely used application in today's world. According to Wikipedia "Google Maps is a web mapping platform and consumer application offered by Google. It offers satellite imagery, aerial photography, street maps, 360° interactive panoramic views of streets, real-time traffic conditions, and route planning for traveling by foot, car, bike, air, and public transportation".
To use Google Maps in an android project we need to go through the following set of rules.
How to use Google Maps
To use maps in android projects we should have an email account and then we will go through the following steps
Step 1
Create a new project by choosing Google Maps Activity and then click on Next, name the application and select the language as java, and target SDK according to your choice
Step 2
Open the AndroidManifest.xml file. In the value of Metadata Tag (see below image), we have to add the Google Maps API from the console.cloud.google.com. To know how to get an API key from Google console in detail, you can follow the given link otherwise simply you can move to step 3 and follow the article.
https://developers.google.com/maps/documentation/android-sdk/get-api-key
Step 3
Go to console.cloud.google.com and log in with your email-id. Now create a project
Select any project, go to Credentials and create a Credential.
Now click on the API key and the following API key will be generated automatically by the Google Cloud. Copy the key and paste it in the value of Meta Tag in the Manifest file.
Now hit the Run Button and run your app. Your app will show the default location as Sydney Australia as shown below.
How to fetch user location in Application
We will fetch the user location in our android application by using a button. We will hit that button and fetch the user location in our maps activity
1. activity_maps.xml file
Add the following controls - EditText,Button,ImageView1(zoom in),ImageView2(zoom out)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
map:layout_constraintTop_toTopOf="parent"
android:id="@+id/edtLocation"
map:layout_constraintLeft_toLeftOf="parent"
/>
<Button
android:id="@+id/btnLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
map:layout_constraintRight_toRightOf="parent"
map:layout_constraintTop_toTopOf="parent"
android:text="Location"
/>
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity"/>
<ImageView
android:id="@+id/imgZoomIn"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@android:drawable/btn_plus"
map:layout_constraintBottom_toTopOf="@id/imgZoomOut"
map:layout_constraintRight_toRightOf="parent"
android:layout_marginEnd="10dp"
/>
<ImageView
android:id="@+id/imgZoomOut"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@android:drawable/btn_minus"
map:layout_constraintBottom_toBottomOf="parent"
map:layout_constraintRight_toRightOf="parent"
android:layout_marginEnd="30dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
2. AndroidManifest.xml file
Add the following 3 permission in the AndroidManifest.xml file and don't forget to add your API key.
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
3. MapsActivity.java file
To add the functionality in controls of zoom in and out buttons just firstly initialize the two imageView and add the setOnClickListener using the following code
binding.imgZoomOut.setOnClickListener(this);
binding.imgZoomIn.setOnClickListener(this);
Here binding is a special feature that allows binding the controls without using R.id.image.Then implements the override methods of OnClickListener and add the following code
@Override
public void onClick(View view) {
Log.i("click_event", "called");
switch (view.getId()) {
case R.id.imgZoomIn:
mMap.animateCamera(CameraUpdateFactory.zoomIn());
break;
case R.id.imgZoomOut:
mMap.animateCamera(CameraUpdateFactory.zoomOut());
break;
case R.id.btnLocation:
getUserCurrentLocation();
setMarkerAtmyLocation();
break;
}
}
Now you can test your buttons of zoom in and zoom out are working fine on the Application or not then we will move to the next step of getting the user's location.
Finding the user's location is done by getting the latitude and longitude from the user and to get this we will move to that by following simple steps-
Step 1
Define the Location Manager, Location listener, and user Current location as follows,
private LocationManager locationManager;
private LocationListener locationListener;
private Location userCurrentLocation;
Here LocationManager is an abstract class which is used to handle the location in android Operating System whereas Locationlistener is and interface which implements the listener of overriding the different functions like LocationChanged, OnProviderEnabled, OnProviderDisabled, OnStatusChange, and many more.
Step 2
Bind the setOnClicklistener as we have done with the zoom in and out button,also add this in Onclick Method to make sure the click works then initialize the locationManager and add two users' defined methods using the following code
binding.btnLocation.setOnClickListener(this);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
initLocationListener();
getUserCurrentLocation();
Step 3
initialize the location listener with the initLocationListener() method and add the different methods as needed we have added 5 following methods to it
private void initLocationListener() {
locationListener = new LocationListener() {
@Override
public void onLocationChanged(@NonNull Location location) {
userCurrentLocation = location;
}
@Override
public void onProviderEnabled(@NonNull String provider) {
LocationListener.super.onProviderEnabled(provider);
Toast.makeText(MapsActivity.this, "Provider Enabled", Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(@NonNull String provider) {
LocationListener.super.onProviderDisabled(provider);
Toast.makeText(MapsActivity.this, "Provider disable", Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
LocationListener.super.onStatusChanged(provider, status, extras);
Toast.makeText(MapsActivity.this, "Status changed", Toast.LENGTH_SHORT).show();
}
};
}
and now we move the define the main method of this article which is getUserCurrentLocation() and to define that we first make sure about the location permissions are provided to the app or not to make sure of that we define a method and user here
private void getUserCurrentLocation() {
if (isPermissionGranted()) {
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.v("method_called", "here");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
isPermissionGranted();
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
} else {
userCurrentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
if (userCurrentLocation != null) {
Log.v("lat_long", "lat:" + userCurrentLocation.getLatitude() + ",longi:" + userCurrentLocation.getLongitude());
binding.edtLocation.setText("lat:" + userCurrentLocation.getLatitude() + ",longi:" + userCurrentLocation.getLongitude());
}
}
here we first check whether the location is provided by the GPS or not if yes we use that else we will ask a network provider about the location and then we will assign that location to our userCurrentLocation .Now half of the work is done and the longitude and latitude is provided as the variable next we have add the marker to the given latitude and longitude in our application fragment.
Step 4
we have to call a method when the user clicks on the location button. so we call the setMarkerAtMyLocation method to set the marker on the Map. Following is the method.
private void setMarkerAtmyLocation() {
if (userCurrentLocation != null) {
mMap.clear();
LatLng myLocation = new LatLng(userCurrentLocation.getLatitude(), userCurrentLocation.getLongitude());
mMap.addMarker(new MarkerOptions().position(myLocation).title("" + userAddress));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation));
}
}
3. Full Code Snippet
package com.example.mapsexample;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.example.mapsexample.databinding.ActivityMapsBinding;
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;
import java.io.IOException;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, View.OnClickListener {
private GoogleMap mMap;
private ActivityMapsBinding binding;
private LocationManager locationManager;
private LocationListener locationListener;
private Location userCurrentLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMapsBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
binding.imgZoomOut.setOnClickListener(this);
binding.imgZoomIn.setOnClickListener(this);
binding.btnLocation.setOnClickListener(this);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
initLocationListener();
getUserCurrentLocation();
}
private void getUserCurrentLocation() {
if (isPermissionGranted()) {
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.v("method_called","here");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
isPermissionGranted();
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
} else {
userCurrentLocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
if (userCurrentLocation!=null) {
Log.v("lat_long", "lat:" + userCurrentLocation.getLatitude() + ",longi:" + userCurrentLocation.getLongitude());
binding.edtLocation.setText("lat:" + userCurrentLocation.getLatitude() + ",longi:" + userCurrentLocation.getLongitude());
}
}
private boolean isPermissionGranted() {
Boolean permissionGranted=true;
String[] permissions=new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
};
if (ActivityCompat.checkSelfPermission(this, permissions[0])!= PackageManager.PERMISSION_GRANTED&&
ActivityCompat.checkSelfPermission(this, permissions[1])!= PackageManager.PERMISSION_GRANTED
){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissions,123);
}
}
return permissionGranted;
}
private void initLocationListener() {
locationListener=new LocationListener() {
@Override
public void onLocationChanged(@NonNull Location location) {
userCurrentLocation=location;
}
@Override
public void onProviderEnabled(@NonNull String provider) {
LocationListener.super.onProviderEnabled(provider);
Toast.makeText(MapsActivity.this, "Provider Enabled", Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(@NonNull String provider) {
LocationListener.super.onProviderDisabled(provider);
Toast.makeText(MapsActivity.this, "Provider disable", Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
LocationListener.super.onStatusChanged(provider, status, extras);
Toast.makeText(MapsActivity.this, "Status changed", Toast.LENGTH_SHORT).show();
}
};
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(28.630863, 77.375475);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker at Electronic city Metro"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
setMarkerAtmyLocation();
}
private void setMarkerAtmyLocation(){
if (userCurrentLocation!=null){
Log.v("curent_lat_long","lat:"+userCurrentLocation.getLatitude()+",longitute:"+userCurrentLocation.getLongitude());
mMap.clear();
Geocoder geocoder=new Geocoder(this);
String userAddress="";
try {
List<Address> addressList=geocoder.getFromLocation(userCurrentLocation.getLatitude(),userCurrentLocation.getLongitude(),5);
Address address=addressList.get(0);
userAddress=address.getLocality()+","+address.getAdminArea()+","+address.getCountryName()+","+address.getPostalCode();
binding.edtLocation.setText(""+userAddress);
} catch (IOException e) {
e.printStackTrace();
}
LatLng myLocation = new LatLng(userCurrentLocation.getLatitude(), userCurrentLocation.getLongitude());
mMap.addMarker(new MarkerOptions().position(myLocation).title(""+userAddress));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation));
}
}
@Override
public void onClick(View view) {
Log.i("click_event","called");
switch (view.getId()){
case R.id.imgZoomIn:
mMap.animateCamera(CameraUpdateFactory.zoomIn());
break;
case R.id.imgZoomOut:
mMap.animateCamera(CameraUpdateFactory.zoomOut());
break;
case R.id.btnLocation:
getUserCurrentLocation();
setMarkerAtmyLocation();
break;
}
}
}
Output
Conclusion
Here in this article, we have discussed how we can use Google maps in any android studio project and how users can fetch their location in this application. This application is easy to use and developers can customize it according to their own usage in their respective projects.