Sun. Dec 16th, 2018

Display current location by a marker on the map in Android

In this tutorial, we will do a basic example of Google Maps. In this example, we will make an app which will show your current location by a marker on the map using Google Maps API. When you click on that marker you can see other details like your Latitude, Longitude, Area, State, and country.

What can Google Maps do for you?

You might have seen the Maps application on your android phone. In your Android Application, you can also have that integrated. There are different purposes for which Google Maps could be used. You can show nearby Banks, current location, calculate a distance between two points and more. A lot of implementations can be done using Google Maps in your app.
Creating New Project – GoogleMapsApp Open your Android Studio & create a new Project named “Googlemaps”, have taken Blank Activity for this project.
The name for activity is by default MainActivity. We kept all the things by default and clicked finish.

Output: – 

Download APK – [media-downloader media_id=”786″ texts=”APK”]

Download Project – [media-downloader media_id=”787″ texts=”project”]

Wants to Learn Android application development from Scratch

Pre-Requisites: –

Before integrating Google Maps you need to have an API Key. For that, you can access
google_maps_api.xml to find an URL. Enter that URL in your web browser and follow rest of the instructions.Create a Google Maps API key, and paste that key in the String called google_maps_key in the same XML file. The key will be starting with “Alza”. Now when you have the API key you may now continue with the development.

Creating Layout

activity_maps.xml

<fragment android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
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"
tools:context="com.mytrendin.googlemapsapp.MapsActivity"/>

All the content of the XML file is self-explanatory but in the case of any queries feel free to comment below.

Creating MapsActivity.java

package com.mytrendin.googlemapsapp;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Showing Current Location Marker on Map
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), true);
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[]
permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the
documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location locations = locationManager.getLastKnownLocation(provider);
List<String> providerList = locationManager.getAllProviders();
if (null != locations && null != providerList && providerList.size() > 0) {
double longitude = locations.getLongitude();
double latitude = locations.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(),
Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(latitude,
longitude, 1);
if (null != listAddresses && listAddresses.size() > 0) {
// Here we are finding , whatever we want our marker to show when
clicked
String state = listAddresses.get(0).getAdminArea();
String country = listAddresses.get(0).getCountryName();
String subLocality = listAddresses.get(0).getSubLocality();
markerOptions.title("" + latLng + "," + subLocality + "," + state
+ "," + country);
}
} catch (IOException e) {
e.printStackTrace();
}
}
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_M
AGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//this code stops location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
this);
}
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "permission denied",
Toast.LENGTH_LONG).show();
}
return;
}
}
}
}

Related:

Periodically send GPS location to Firebase with custom time frame in Android

Draw route and calculate distance between two locations in Google Maps Android

Display current location(latitude and longitude) in google map and save it to the Firebase database in Android

Store data using SQLite by fetching from ContentProvider and display using RecyclerView

Get the current location and show it by custom marker in Google map

Best security tips for android phone

Secure phone contacts on your gmail account

5+ best free YouTube intro maker websites

We will provide our Activity the view of activity_maps by writing

setContentView(R.layout.activity_maps);

New versions of Android allow the user to have specific permissions enables and rest disabled. Therefore not all the permissions will be accepted by default in those Android Versions. So we will apply a Version check before executing our code. If the Android Version is equal or above the Marshmallow version then permission has to be granted first manually by the user.

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}

Obtain the SupportMapFragment and get notified when our Map is ready to be used.

SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);

OnMapReady is a Callback Interface which executes when Map is ready to be used. In case the Google Play Services is not installed on the device, then the user will be prompted to install it. After the user will install it and return to the app then only this method will be triggered.

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}

onConnected(Bundle bundle) will be used to start making API requests when the client is connected to the service.

@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
}

Whenever your location changes, your marker should also shift. Therefore at that time
onLocationChanged method will be called, and a current marker will be removed and new will be applied.

mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}

Now on the Map, we want to add Marker to show the current location of the user. So that
implementation will be done by fetching the current Latitudes and Longitudes first. Later on, we will apply the marker corresponding to those coordinates. Hence, obtaining the marker at your current location. For that, we will be creating an object of LatLng (which is an immutable class representing a pair of latitude and longitude coordinates, stored as degrees). Later we will apply marker on our Map, using the value in this object.

LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);

Now we have to apply some specific data on our marker. So we will apply all that in the title of that marker which can be seen when the marker is clicked by the user. We will use Latitudes and Longitudes with Geocoder class to get information regarding the current city, Country etc. LocationManager Class will provide us access to system location services. Using which we can get geographical locations of our device. Geocoder class, on the other hand, provides us functionality to transform a latitude and longitude combination into a street address or can also help us do the reverse of that. We will use a list to store our current location details. And then using that value we according to our requirement can fetch State, Country name, Sub-Locality etc.

Then we apply all these to our Marker’s title using object of MarkerOptions class.

LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), true);
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[]
permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the
documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location locations = locationManager.getLastKnownLocation(provider);
List<String> providerList = locationManager.getAllProviders();
if (null != locations && null != providerList && providerList.size() > 0) {
double longitude = locations.getLongitude();
double latitude = locations.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(),
Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(latitude,
longitude, 1);
if (null != listAddresses && listAddresses.size() > 0) {
// Here we are finding , whatever we want our marker to show when
clicked
String state = listAddresses.get(0).getAdminArea();
String country = listAddresses.get(0).getCountryName();
String subLocality = listAddresses.get(0).getSubLocality();
markerOptions.title("" + latLng + "," + subLocality + "," + state
+ "," + country);
}
} catch (IOException e) {
e.printStackTrace();
}
}
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_M
AGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//this code stops location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
this);
}
}

Rest of the code written is in support of the Permission check we applied initially. It is self-explanatory but feels free to ask any query. If the user allows the permission for this particular access then the permission will be allowed else denied.

If You are Beginner Learn Android application development from the scratch

AndroidManifest.xml

We have to give permissions for ACCESS_FINE_LOCATION in our manifest file so that we can access “MyLocation” functionality. We use meta-data tag to mention the API Key over here in the manifest. It is a name-value pair for an item of additional, arbitrary data that is provided to the parent component.

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.mytrendin.googlemapsapp"
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key"/>
<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.




6 thoughts on “Display current location by a marker on the map in Android

  1. Hello, first of all I love the job you are doing with these articles. so my questions is if I want to show the markers from a database, where should I implement this?

  2. When I click download, it gives me a motivational handbook. I didn’t +1 for this. Where may I download this?

Leave a Reply

Your email address will not be published. Required fields are marked *