Mobile App Dev T Google Maps
Mobile App Dev T Google Maps
Mobile App Dev T Google Maps
An API key is needed to access the Google Maps servers. This key is free and you can
use it with any of your applications. If you haven’t created project, you can follow the
below steps to get started:
Step 1: Open Google developer console and signin with your gmail
account: https://console.developers.google.com/project
Step 2: Now create new project. You can create new project by clicking on the Create
Project button and give name to your project.
Step 3: Now click on APIs & Services and open Dashboard from it.
Step 8: Now API your API key will be generated. Copy it and save it somewhere as we
will need it when implementing Google Map in our Android project.
Google Maps Example To Access User Current Location In Android Studio:
In the below Google Map example we will show user current location in Map. We also
example different map types, methods and lots more details required while
implementing Map in Android.
Below you can download code, see final output and step by step explanation of example:
Download Code
Step 2: Now select Google Maps Activity and then click Next and finish.
Step 3: Now open google_maps_api.xml (debug) in values folder
Step 4: Here enter your Google Maps API key in place of YOUR_KEY_HERE. In case
you skip article, earlier we have guided how to get your own Google Maps Api key:
<resources>
<!--
TODO: Before you run your application, you need a Google Maps API key.
To get one, follow this link, follow the directions and press "Create" at the end:
https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_S
IDE_ANDROID&r=8B:49:70:2A:08:F2:23:14:CF:A1:FC:6F:6D:5B:60:3C:B6:85:98:F2%3Bcom.example.abhi
shek.googlemaps
You can also add your credentials to an existing key, using these values:
Package name:
8B:49:70:2A:08:F2:23:14:CF:A1:FC:6F:6D:5B:60:3C:B6:85:98:F2
8B:49:70:2A:08:F2:23:14:CF:A1:FC:6F:6D:5B:60:3C:B6:85:98:F2
https://developers.google.com/maps/documentation/android/start#get-key
Once you have your key (it starts with "AIza"), replace the "google_maps_key"
-->
</resources>
build.gradle code
android {
compileSdkVersion 26
buildToolsVersion "26.0.2"
defaultConfig {
applicationId "com.abhiandroid.GoogleMaps.googlemaps"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
buildTypes {
release {
minifyEnabled false
dependencies {
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.google.android.gms:play-services:8.4.0'
testCompile 'junit:junit:4.12'
activity_maps.xml code
<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.abhiandroid.GoogleMaps.googlemaps.MapsActivity"/>
AndroidManifest.xml code:
<manifest package="com.abhiandroid.GoogleMaps.googlemaps"
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<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="com.abhiandroid.GoogleMaps.googlemaps.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>
Step 7: Now we will code MapsActivity.java file for inserting callbacks in Google
Maps:
@Override
@Override
@Override
@Override
@Override
@Override
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
-Zoom Controls: The Maps API provides built-in zoom controls that appear in the
bottom right hand corner of the map. These can be enabled by calling:
mMap.getUiSettings().setZoomControlsEnabled(true);
-Zoom Gestures:
mMap.getUiSettings().setZoomGesturesEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
The Android Maps API provides normal, satellite, terrain and hybrid map types to help
you out:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
MAP_TYPE_NORMAL : Represents a typical road map with street names and labels.
Add the following inside setUpMap() just below the setMyLocationEnabled() call:
The location of the user is updated at the regular intervals. We have used
FusedLocationProvider. We have used requestLocationUpdates() method to get regular
updates about a device’s location. Do this in the onConnected() callback provided by
Google API Client, which is called when the client is ready.
@Override
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 user’s location is changed. For that Google has predefined function
onLocationChanged that will be called as soon as user’s location change. Here we are
getting the coordinates of current location using getLatitude() and getLongitude() and
we are also adding Marker.
package com.abhiandroid.GoogleMaps.googlemaps;
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 com.abhiandroid.GoogleMaps.googlemaps.R;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
checkLocationPermission();
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
@Override
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
@Override
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
@Override
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
markerOptions.position(latLng);
getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
Locale.getDefault());
try {
longitude, 1);
+ "," + country);
}
} catch (IOException e) {
e.printStackTrace();
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
mCurrLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
this);
@Override
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
return false;
} else {
return true;
@Override
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
} else {
Toast.LENGTH_LONG).show();
}
return;
Output:
Now run the App. If you are connected to internet and provide access to your location
then in Map you will see your current location.
In this example, we are drawing path between two locations using Polylines. In this we
define origin and dest latlng. After that we get direction urls and then
execute AsyncTask class to get data from direction API. In the end, we parse direction
data and then use PolylineOptions to draw the path between two locations.
AsyncTask is used to perform long running operations and show its result on the UI
thread.
Step 1: Create a new project and name It MapExample.
Step 2: Open Gradle Scripts > build.gradle and add Retrofit and RecyclerView Library
dependency in it.
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.abhiandroid.MapRouteExample"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
buildTypes {
release {
minifyEnabled false
dependencies {
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.google.android.gms:play-services:7.8.0'
For network transactions we need to define Internet and other map permissions in our
Manifest file. Add meta-data with the google map key you get from google console.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.abhiandroid.MapRouteExample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name="com.abhiandroid.MapRouteExample.MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyDagu1__IQVkCjlGIGYkbdUf-JcJ0hofZ0" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
</application>
</manifest>
Step 4: Open res -> layout -> activity_main.xml (or) main.xml and add following
code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.abhiandroid.MapRouteExample.MainActivity"
tools:showIn="@layout/activity_main">
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_gravity="center"
android:layout_height="match_parent"
/>
</RelativeLayout>
Step 5: Create a new class DirectionsJSONParser.java in which we have parse method
to parse the data which we get from direction API.
package com.abhiandroid.MapRouteExample;
import com.google.android.gms.maps.model.LatLng;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/** Receives a JSONObject and returns a list of lists containing latitude and longitude */
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
for(int j=0;j<jLegs.length();j++){
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
for(int k=0;k<jSteps.length();k++){
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
routes.add(path);
} catch (JSONException e) {
e.printStackTrace();
return routes;
do {
b = encoded.charAt(index++) - 63;
shift += 5;
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
lng += dlng;
poly.add(p);
return poly;
Step 6: Now open app -> java -> package -> MainActivity.java and add the below code.
In this step, firstly we get reference of Support Map Fragment that we defined in our
xml file and then set the marker on both locations in onMapReady callback. After that
we get direction urls and then execute AsyncTask class to get data from direction API.
In the end, we parse direction data and then use PolylineOptions to draw the path
between two locations.
package com.abhiandroid.MapRouteExample;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
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.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
SupportMapFragment mapFragment;
GoogleMap mMap;
ProgressDialog progressDialog;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
drawPolylines();
progressDialog.setCancelable(false);
progressDialog.show();
downloadTask.execute(url);
}
@Override
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
@Override
// Handle action bar item clicks here. The action bar will
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
return super.onOptionsItemSelected(item);
@Override
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.addMarker(new MarkerOptions()
.position(origin)
.title("LinkedIn")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
googleMap.addMarker(new MarkerOptions()
.position(dest));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(origin, 15));
@Override
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
return data;
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
parserTask.execute(result);
/**
*/
@Override
JSONObject jObject;
try {
} catch (Exception e) {
e.printStackTrace();
return routes;
@Override
progressDialog.dismiss();
Log.d("result", result.toString());
lineOptions.addAll(points);
lineOptions.width(12);
lineOptions.color(Color.RED);
lineOptions.geodesic(true);
mMap.addPolyline(lineOptions);
// Origin of route
// Destination of route
// Sensor enabled
return url;
/**
*/
try {
urlConnection.connect();
iStream = urlConnection.getInputStream();
sb.append(line);
data = sb.toString();
br.close();
Log.d("data", data);
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
return data;