{"id":781,"date":"2018-03-09T06:00:34","date_gmt":"2018-03-09T06:00:34","guid":{"rendered":"http:\/\/abhiandroid.com\/programming\/?page_id=781"},"modified":"2019-06-14T11:37:25","modified_gmt":"2019-06-14T11:37:25","slug":"googlemaps","status":"publish","type":"page","link":"https:\/\/abhiandroid.com\/programming\/googlemaps","title":{"rendered":"Google Maps Tutorial With Example In Android Studio [Step by Step]"},"content":{"rendered":"<p>Android allows us to integrate Google Maps in our application. For this Google provides us a library via Google Play Services for using maps.\u00a0In order to use the Google Maps API, you must register your application on the\u00a0<strong>Google Developer Console<\/strong>\u00a0and enable the API.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-874\" src=\"\/programming\/wp-content\/uploads\/2018\/01\/Google-Map-Example-In-Android-Studio.gif\" alt=\"Google Map Example In Android Studio\" width=\"258\" height=\"478\" \/><\/p>\n<hr \/>\n<h4><strong>Steps For Getting The Google Maps Api Key:<\/strong><\/h4>\n<p>An API key is needed\u00a0 to access the Google Maps servers. \u00a0This key is free and you can use it with any of your applications. If you haven&#8217;t created project, you can follow the below steps to get started:<\/p>\n<p><strong>Step 1:<\/strong> Open Google developer console and signin with your gmail account:\u00a0<a href=\"https:\/\/console.developers.google.com\/project\">https:\/\/console.developers.google.com\/project<\/a><\/p>\n<p><strong>Step 2:\u00a0<\/strong>Now create new project. You can create new project by clicking on\u00a0the\u00a0<strong>Create Project<\/strong>\u00a0button and give name to your project.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-851\" src=\"\/programming\/wp-content\/uploads\/2018\/01\/Create-new-project.png\" alt=\"Create-new-project\" width=\"482\" height=\"133\" srcset=\"https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2018\/01\/Create-new-project.png 482w, https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2018\/01\/Create-new-project-300x83.png 300w\" sizes=\"auto, (max-width: 482px) 100vw, 482px\" \/><\/p>\n<p><b>Step 3:<\/b>\u00a0Now click on APIs &amp; Services and open\u00a0<strong>Dashboard<\/strong>\u00a0from it.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-852\" src=\"\/programming\/wp-content\/uploads\/2018\/01\/Open-Dashboard.png\" alt=\"Open-Dashboard\" width=\"320\" height=\"210\" srcset=\"https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2018\/01\/Open-Dashboard.png 320w, https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2018\/01\/Open-Dashboard-300x197.png 300w\" sizes=\"auto, (max-width: 320px) 100vw, 320px\" \/><\/p>\n<p><strong>Step 4:<\/strong> In this open\u00a0<strong>Enable APIS AND SERICES<\/strong>.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-854\" src=\"\/programming\/wp-content\/uploads\/2018\/01\/Enable-api.png\" alt=\"Enable-api\" width=\"461\" height=\"157\" srcset=\"https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2018\/01\/Enable-api.png 461w, https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2018\/01\/Enable-api-300x102.png 300w\" sizes=\"auto, (max-width: 461px) 100vw, 461px\" \/><\/p>\n<p><strong>Step 5:<\/strong> Now open Google Map Android API.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-855\" src=\"\/programming\/wp-content\/uploads\/2018\/01\/open-google-map-api.png\" alt=\"Open-google-map-api\" width=\"419\" height=\"222\" srcset=\"https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2018\/01\/open-google-map-api.png 419w, https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2018\/01\/open-google-map-api-300x159.png 300w\" sizes=\"auto, (max-width: 419px) 100vw, 419px\" \/><\/p>\n<p><strong>Step 6:<\/strong> Now enable the Google Maps Android API.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-856\" src=\"\/programming\/wp-content\/uploads\/2018\/01\/Enable-Google-Maps-API.png\" alt=\"Enable-Google-Maps-API\" width=\"421\" height=\"175\" srcset=\"https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2018\/01\/Enable-Google-Maps-API.png 421w, https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2018\/01\/Enable-Google-Maps-API-300x125.png 300w\" sizes=\"auto, (max-width: 421px) 100vw, 421px\" \/><\/p>\n<p><strong>Step 6:<\/strong> Now go to<strong>\u00a0Credentials<\/strong><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-857\" src=\"\/programming\/wp-content\/uploads\/2018\/01\/Open-Credentials.png\" alt=\"Open-Credentials\" width=\"249\" height=\"211\" \/><\/p>\n<p><strong>Step 7: <\/strong>\u00a0Here click on Create credentials and choose API key<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-858\" src=\"\/programming\/wp-content\/uploads\/2018\/01\/Create-Google-Map-API-credentials.png\" alt=\"Create-Google-Map-API-credentials\" width=\"428\" height=\"298\" srcset=\"https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2018\/01\/Create-Google-Map-API-credentials.png 428w, https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2018\/01\/Create-Google-Map-API-credentials-300x209.png 300w\" sizes=\"auto, (max-width: 428px) 100vw, 428px\" \/><\/p>\n<p><strong>Step 8:<\/strong> 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.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-859\" src=\"\/programming\/wp-content\/uploads\/2018\/01\/Google-Map-api-key-created.png\" alt=\"Google-Map-api-key-created\" width=\"499\" height=\"251\" srcset=\"https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2018\/01\/Google-Map-api-key-created.png 499w, https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2018\/01\/Google-Map-api-key-created-300x151.png 300w\" sizes=\"auto, (max-width: 499px) 100vw, 499px\" \/><\/p>\n<hr \/>\n<h4><strong>Google Maps Example To Access User Current Location In Android Studio:<\/strong><\/h4>\n<p>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.<\/p>\n<p>Below you can download code, see final output and step by step explanation of example:<\/p>\n<p style=\"text-align: center;\"><a class=\"download\" href=\"http:\/\/www.mediafire.com\/file\/041dknu2e4p6n6r\/GoogleMaps.zip\/file\" target=\"_blank\" rel=\"nofollow noopener\">Download Code<\/a><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-874\" src=\"\/programming\/wp-content\/uploads\/2018\/01\/Google-Map-Example-In-Android-Studio.gif\" alt=\"Google Map Example In Android Studio\" width=\"258\" height=\"478\" \/><\/p>\n<p><strong>Step 1:<\/strong> Create a New Android Project and name it GoogleMaps.<\/p>\n<p><strong>Step 2:<\/strong> Now select Google Maps Activity and then click Next and finish.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-862\" src=\"\/programming\/wp-content\/uploads\/2018\/01\/Choose-Map-Activity-Android-Studio.png\" alt=\"Choose-Map-Activity-Android-Studio\" width=\"489\" height=\"353\" srcset=\"https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2018\/01\/Choose-Map-Activity-Android-Studio.png 489w, https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2018\/01\/Choose-Map-Activity-Android-Studio-300x217.png 300w\" sizes=\"auto, (max-width: 489px) 100vw, 489px\" \/><\/p>\n<p><strong>Step 3:<\/strong> Now open <strong>google_maps_api.xml<\/strong> (debug) in values folder<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-866\" src=\"\/programming\/wp-content\/uploads\/2018\/01\/Google-Maps-API-xml-android-studio.png\" alt=\"Google-Maps-API-xml-android-studio\" width=\"599\" height=\"220\" srcset=\"https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2018\/01\/Google-Maps-API-xml-android-studio.png 599w, https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2018\/01\/Google-Maps-API-xml-android-studio-300x110.png 300w\" sizes=\"auto, (max-width: 599px) 100vw, 599px\" \/><\/p>\n<p><strong>Step 4:<\/strong> 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:<\/p>\n<pre>&lt;resources&gt;\r\n    &lt;!--\r\n    TODO: Before you run your application, you need a Google Maps API key.\r\n\r\n    To get one, follow this link, follow the directions and press \"Create\" at the end:\r\n\r\n    https:\/\/console.developers.google.com\/flows\/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=8B:49:70:2A:08:F2:23:14:CF:A1:FC:6F:6D:5B:60:3C:B6:85:98:F2%3Bcom.example.abhishek.googlemaps\r\n\r\n    You can also add your credentials to an existing key, using these values:\r\n\r\n    Package name:\r\n    8B:49:70:2A:08:F2:23:14:CF:A1:FC:6F:6D:5B:60:3C:B6:85:98:F2\r\n\r\n    SHA-1 certificate fingerprint:\r\n    8B:49:70:2A:08:F2:23:14:CF:A1:FC:6F:6D:5B:60:3C:B6:85:98:F2\r\n\r\n    Alternatively, follow the directions here:\r\n    https:\/\/developers.google.com\/maps\/documentation\/android\/start#get-key\r\n\r\n    Once you have your key (it starts with \"AIza\"), replace the \"google_maps_key\"\r\n    string in this file.\r\n    --&gt;\r\n    &lt;string name=\"google_maps_key\" templateMergeStrategy=\"preserve\" translatable=\"false\"&gt;AIzaSyDV2_xy58r15K6TskZy4KWMuhUDVq67jqM&lt;\/string&gt;\r\n&lt;\/resources&gt;<\/pre>\n<p><strong>Step 5: <\/strong>Now open build.gradle and add compile &#8216;com.google.android.gms:play-services:8.4.0&#8217; in dependencies<\/p>\n<p><strong>build.gradle code<\/strong><\/p>\n<pre>apply plugin: 'com.android.application'\r\n\r\nandroid {\r\n    compileSdkVersion 26\r\n    buildToolsVersion \"26.0.2\"\r\n    defaultConfig {\r\n        applicationId \"com.abhiandroid.GoogleMaps.googlemaps\"\r\n        minSdkVersion 15\r\n        targetSdkVersion 26\r\n        versionCode 1\r\n        versionName \"1.0\"\r\n        testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\r\n    }\r\n    buildTypes {\r\n        release {\r\n            minifyEnabled false\r\n            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r\n        }\r\n    }\r\n}\r\n\r\ndependencies {\r\n    compile fileTree(dir: 'libs', include: ['*.jar'])\r\n    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {\r\n        exclude group: 'com.android.support', module: 'support-annotations'\r\n    })\r\n    compile 'com.android.support:appcompat-v7:26.+'\r\n    compile 'com.google.android.gms:play-services:8.4.0'\r\n    testCompile 'junit:junit:4.12'\r\n}<\/pre>\n<p id=\"add_a_fragment\"><strong>Step 6:<\/strong>\u00a0Now open activity_maps.xml and add a fragment code in it<\/p>\n<p>Here add a\u00a0fragment\u00a0element to the activity&#8217;s layout file to define a\u00a0Fragment\u00a0object. In this element, set the\u00a0android:name\u00a0attribute to\u00a0&#8220;com.google.android.gms.maps.MapFragment&#8221;. This automatically attaches a\u00a0MapFragment\u00a0to the activity. The following layout file contains a\u00a0fragment\u00a0element:<\/p>\n<p><strong>activity_maps.xml code<\/strong><\/p>\n<pre>&lt;fragment android:id=\"@+id\/map\"\r\n    android:name=\"com.google.android.gms.maps.SupportMapFragment\"\r\n    xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    xmlns:map=\"http:\/\/schemas.android.com\/apk\/res-auto\"\r\n    xmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\n    android:layout_width=\"match_parent\"\r\n    android:layout_height=\"match_parent\"\r\n    tools:context=\"com.abhiandroid.GoogleMaps.googlemaps.MapsActivity\"\/&gt;<\/pre>\n<p><strong>Step 6:<\/strong> Now define internet and location permissions in Android Manifest<\/p>\n<p><strong>INTERNET<\/strong>\u00a0\u2013 To determine if we are connected to Internet or not.<br \/>\n<strong>ACCESS_FINE_LOCATION<\/strong>\u00a0\u2013 To determine user\u2019s location using GPS. It will give us precise location.<\/p>\n<p><strong>AndroidManifest.xml code:<\/strong><\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;manifest package=\"com.abhiandroid.GoogleMaps.googlemaps\"\r\n    xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"&gt;\r\n    &lt;uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\"\/&gt;\r\n    &lt;uses-permission android:name=\"android.permission.INTERNET\"\/&gt;\r\n    &lt;application\r\n        android:allowBackup=\"true\"\r\n        android:icon=\"@mipmap\/ic_launcher\"\r\n        android:label=\"@string\/app_name\"\r\n        android:supportsRtl=\"true\"\r\n        android:theme=\"@style\/AppTheme\"&gt;\r\n        &lt;meta-data\r\n            android:name=\"com.google.android.geo.API_KEY\"\r\n            android:value=\"@string\/google_maps_key\"\/&gt;\r\n        &lt;activity\r\n            android:name=\"com.abhiandroid.GoogleMaps.googlemaps.MapsActivity\"\r\n            android:label=\"@string\/title_activity_maps\"&gt;\r\n            &lt;intent-filter&gt;\r\n                &lt;action android:name=\"android.intent.action.MAIN\"\/&gt;\r\n                &lt;category android:name=\"android.intent.category.LAUNCHER\"\/&gt;\r\n            &lt;\/intent-filter&gt;\r\n        &lt;\/activity&gt;\r\n    &lt;\/application&gt;\r\n&lt;\/manifest&gt;\r\n\r\n<\/pre>\n<p><strong>Step 7:<\/strong> Now we will code MapsActivity.java file for inserting callbacks in Google Maps:<\/p>\n<p><strong>-OnMapReadyCallback:<\/strong> This callback is called when the map is ready to be used<\/p>\n<pre>@Override\r\npublic void onMapReady(GoogleMap googleMap) {}<\/pre>\n<p><strong>-GoogleApiClient.ConnectionCallbacks<\/strong>: This callback\u00a0 is called whenever device is connected and disconnected and implement onConnected() and onConnectionSuspended() functions.<\/p>\n<pre>\/\/When the connect request has successfully completed\r\n@Override\r\npublic void onConnected(Bundle bundle) {}\r\n\r\n<\/pre>\n<pre>\/\/Called when the client is temporarily in a disconnected state.\r\n@Override\r\npublic void onConnectionSuspended(int i) {\r\n}<\/pre>\n<p><strong>-GoogleApiClient.OnConnectionFailedListener<\/strong>: Provides callbacks for scenarios that result in a failed attempt to connect the client to the service. Whenever connection is failed onConnectionFailed() will be called.<\/p>\n<pre>@Override\r\npublic void onConnectionFailed(ConnectionResult connectionResult) {\r\n}<\/pre>\n<p><strong>-LocationListener<\/strong>: This callback have\u00a0 function onLocationChanged() that will be called whenever there is change in location of device.<\/p>\n<pre>@Override\r\npublic void onLocationChanged(Location location) {}<\/pre>\n<p><strong>-onMapReady(): <\/strong>This function is called when the map is ready to be used.<\/p>\n<p><strong>-buildGoogleApiClient():<\/strong>\u00a0This method is used to initialize the Google Play Services.<\/p>\n<pre>@Override\r\npublic void onMapReady(GoogleMap googleMap) {\r\n    mMap = googleMap;\r\n    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);\r\n    mMap.getUiSettings().setZoomControlsEnabled(true);\r\n    mMap.getUiSettings().setZoomGesturesEnabled(true);\r\n    mMap.getUiSettings().setCompassEnabled(true);\r\n\r\n    \/\/Initialize Google Play Services\r\n    if (android.os.Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M) {\r\n        if (ContextCompat.checkSelfPermission(this,\r\n                Manifest.permission.ACCESS_FINE_LOCATION)\r\n                == PackageManager.PERMISSION_GRANTED) {\r\n            buildGoogleApiClient();\r\n            mMap.setMyLocationEnabled(true);\r\n        }\r\n    } else {\r\n        buildGoogleApiClient();\r\n        mMap.setMyLocationEnabled(true);\r\n    }\r\n}<\/pre>\n<p><strong>-addConnectionCallbacks():<\/strong>\u00a0You need\u00a0 to call registers a listener to receive connection events from this GoogleApiClient.<\/p>\n<p><strong>-addOnConnectionFailedListener():<\/strong>\u00a0This methods adds a listener to register to receive connection failed events from this GoogleApiClient.<\/p>\n<p><strong>-GoogleApiClient.Builder:<\/strong>\u00a0Builder is used to help construct the GoogleApiClient object and\u00a0addApi\u00a0<span class=\"params\">() specify which Apis are requested by your app.<\/span><\/p>\n<p><strong>-mGoogleApiClient.connect():<\/strong> A client must be connected before executing any operation.<\/p>\n<pre>protected synchronized void buildGoogleApiClient() {\r\n mGoogleApiClient = new GoogleApiClient.Builder(this)\r\n .addConnectionCallbacks(this)\r\n .addOnConnectionFailedListener(this)\r\n .addApi(LocationServices.API)\r\n .build();\r\n mGoogleApiClient.connect();\r\n}\r\n\r\n<\/pre>\n<p><strong>-Zoom Controls:<\/strong>\u00a0The Maps API provides built-in zoom controls that appear in the bottom right hand corner of the map. These can be enabled by calling:<\/p>\n<pre>mMap.getUiSettings().setZoomControlsEnabled(true);\r\n<\/pre>\n<p><strong>-Zoom Gestures:<\/strong><\/p>\n<p><strong>ZoomIn<\/strong>: Double tap to increase the zoom level by 1.<\/p>\n<p><strong>Zoom Out<\/strong>: Two finger tap to decrease the zoom level by 1.<\/p>\n<pre>mMap.getUiSettings().setZoomGesturesEnabled(true);<\/pre>\n<p><strong>-Compass:<\/strong>\u00a0You can set compass by calling below method:<\/p>\n<pre>mMap.getUiSettings().setCompassEnabled(true);\r\n<\/pre>\n<p><strong>-Changing the Map Type:<\/strong><\/p>\n<p>The Android Maps API provides normal, satellite, terrain and hybrid map types to help you out:<\/p>\n<pre>mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);\r\nmMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);\r\nmMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);\r\nmMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);<\/pre>\n<p><strong>MAP_TYPE_NORMAL : <\/strong>Represents a typical road map with street names and labels.<\/p>\n<p><strong>MAP_TYPE_SATELLITE: <\/strong>Represents a\u00a0Satellite View Area without street names and labels.<\/p>\n<p><strong>MAP_TYPE_TERRAIN:\u00a0<\/strong>Topographic data. The map includes colors, contour lines and labels, and perspective shading. Some roads and labels are also visible.<\/p>\n<p><strong>MAP_TYPE_HYBRID : <\/strong>Combines\u00a0a satellite View Area and Normal mode displaying\u00a0satellite images of an area with all labels.<\/p>\n<p><strong>Map_TYPE_NONE<\/strong> : No tiles. It is similar to a normal map, but doesn&#8217;t display any labels or coloration for the type of environment in an area.<\/p>\n<p>Add the following inside\u00a0setUpMap()\u00a0just below the setMyLocationEnabled() call:<\/p>\n<p>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&#8217;s location. Do this in the onConnected()\u00a0callback provided by Google API Client, which is called when the client is ready.<\/p>\n<p>LocationRequest mLocationRequest is used to get quality of service for location updates from the FusedLocationProviderApi using requestLocationUpdates.<\/p>\n<pre>@Override\r\npublic void onConnected(Bundle bundle) {\r\n    mLocationRequest = new LocationRequest();\r\n    mLocationRequest.setInterval(1000);\r\n    mLocationRequest.setFastestInterval(1000);\r\n    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);\r\n    if (ContextCompat.checkSelfPermission(this,\r\n            Manifest.permission.ACCESS_FINE_LOCATION)\r\n            == PackageManager.PERMISSION_GRANTED) {\r\n     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,\r\n                mLocationRequest, this);\r\n    }\r\n}\r\n<\/pre>\n<p>Whenever user&#8217;s location is changed. For that Google has predefined function onLocationChanged that will be called as soon as user&#8217;s location change. Here we are getting the coordinates of current location using getLatitude() and getLongitude() and we are also adding Marker.<\/p>\n<p><strong>Complete code of MapsActivity.java class:<\/strong><\/p>\n<pre>package com.abhiandroid.GoogleMaps.googlemaps;\r\nimport android.Manifest;\r\nimport android.content.Context;\r\nimport android.content.pm.PackageManager;\r\nimport android.location.Address;\r\nimport android.location.Criteria;\r\nimport android.location.Geocoder;\r\nimport android.location.Location;\r\nimport android.location.LocationManager;\r\nimport android.os.Build;\r\nimport android.os.Bundle;\r\nimport android.support.v4.app.ActivityCompat;\r\nimport android.support.v4.app.FragmentActivity;\r\nimport android.support.v4.content.ContextCompat;\r\nimport android.widget.Toast;\r\nimport com.google.android.gms.common.ConnectionResult;\r\nimport com.google.android.gms.common.api.GoogleApiClient;\r\nimport com.google.android.gms.location.LocationListener;\r\nimport com.google.android.gms.location.LocationRequest;\r\nimport com.google.android.gms.location.LocationServices;\r\nimport com.google.android.gms.maps.CameraUpdateFactory;\r\nimport com.google.android.gms.maps.GoogleMap;\r\nimport com.google.android.gms.maps.OnMapReadyCallback;\r\nimport com.google.android.gms.maps.SupportMapFragment;\r\nimport com.google.android.gms.maps.model.BitmapDescriptorFactory;\r\nimport com.google.android.gms.maps.model.LatLng;\r\nimport com.google.android.gms.maps.model.Marker;\r\nimport com.google.android.gms.maps.model.MarkerOptions;\r\nimport com.abhiandroid.GoogleMaps.googlemaps.R;\r\n\r\nimport java.io.IOException;\r\nimport java.util.List;\r\nimport java.util.Locale;\r\npublic class MapsActivity extends FragmentActivity implements OnMapReadyCallback,\r\n        GoogleApiClient.ConnectionCallbacks,\r\n        GoogleApiClient.OnConnectionFailedListener,\r\n        LocationListener {\r\n    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;\r\n    GoogleApiClient mGoogleApiClient;\r\n    Location mLastLocation;\r\n    Marker mCurrLocationMarker;\r\n    LocationRequest mLocationRequest;\r\n    private GoogleMap mMap;\r\n    @Override\r\n    protected void onCreate(Bundle savedInstanceState) {\r\n        super.onCreate(savedInstanceState);\r\n        setContentView(R.layout.activity_maps);\r\n\r\n        if (android.os.Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M) {\r\n            checkLocationPermission();\r\n        }\r\n        SupportMapFragment mapFragment = (SupportMapFragment)\r\n                getSupportFragmentManager()\r\n                        .findFragmentById(R.id.map);\r\n\r\n        mapFragment.getMapAsync(this);\r\n    }\r\n    @Override\r\n    public void onMapReady(GoogleMap googleMap) {\r\n        mMap = googleMap;\r\n        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);\r\n        mMap.getUiSettings().setZoomControlsEnabled(true);\r\n        mMap.getUiSettings().setZoomGesturesEnabled(true);\r\n        mMap.getUiSettings().setCompassEnabled(true);\r\n        \/\/Initialize Google Play Services\r\n        if (android.os.Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M) {\r\n            if (ContextCompat.checkSelfPermission(this,\r\n                    Manifest.permission.ACCESS_FINE_LOCATION)\r\n                    == PackageManager.PERMISSION_GRANTED) {\r\n                buildGoogleApiClient();\r\n                mMap.setMyLocationEnabled(true);\r\n            }\r\n        } else {\r\n            buildGoogleApiClient();\r\n            mMap.setMyLocationEnabled(true);\r\n        }\r\n    }\r\n    protected synchronized void buildGoogleApiClient() {\r\n        mGoogleApiClient = new GoogleApiClient.Builder(this)\r\n                .addConnectionCallbacks(this)\r\n                .addOnConnectionFailedListener(this)\r\n                .addApi(LocationServices.API)\r\n                .build();\r\n        mGoogleApiClient.connect();\r\n    }\r\n    @Override\r\n    public void onConnected(Bundle bundle) {\r\n        mLocationRequest = new LocationRequest();\r\n        mLocationRequest.setInterval(1000);\r\n        mLocationRequest.setFastestInterval(1000);\r\n        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);\r\n        if (ContextCompat.checkSelfPermission(this,\r\n                Manifest.permission.ACCESS_FINE_LOCATION)\r\n                == PackageManager.PERMISSION_GRANTED) {\r\n            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,\r\n                    mLocationRequest, this);\r\n        }\r\n    }\r\n    @Override\r\n    public void onConnectionSuspended(int i) {\r\n    }\r\n    @Override\r\n    public void onLocationChanged(Location location) {\r\n        mLastLocation = location;\r\n        if (mCurrLocationMarker != null) {\r\n            mCurrLocationMarker.remove();\r\n        }\r\n\/\/Showing Current Location Marker on Map\r\n        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());\r\n        MarkerOptions markerOptions = new MarkerOptions();\r\n        markerOptions.position(latLng);\r\n        LocationManager locationManager = (LocationManager)\r\n                getSystemService(Context.LOCATION_SERVICE);\r\n        String provider = locationManager.getBestProvider(new Criteria(), true);\r\n        if (ActivityCompat.checkSelfPermission(this,\r\n                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &amp;&amp;\r\n                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)\r\n                        != PackageManager.PERMISSION_GRANTED) {\r\n            return;\r\n        }\r\n        Location locations = locationManager.getLastKnownLocation(provider);\r\n        List&lt;String&gt; providerList = locationManager.getAllProviders();\r\n        if (null != locations &amp;&amp; null != providerList &amp;&amp; providerList.size() &gt; 0) {\r\n            double longitude = locations.getLongitude();\r\n            double latitude = locations.getLatitude();\r\n            Geocoder geocoder = new Geocoder(getApplicationContext(),\r\n                    Locale.getDefault());\r\n            try {\r\n                List&lt;Address&gt; listAddresses = geocoder.getFromLocation(latitude,\r\n                        longitude, 1);\r\n                if (null != listAddresses &amp;&amp; listAddresses.size() &gt; 0) {\r\n                    String state = listAddresses.get(0).getAdminArea();\r\n                    String country = listAddresses.get(0).getCountryName();\r\n                    String subLocality = listAddresses.get(0).getSubLocality();\r\n                    markerOptions.title(\"\" + latLng + \",\" + subLocality + \",\" + state\r\n                            + \",\" + country);\r\n                }\r\n            } catch (IOException e) {\r\n                e.printStackTrace();\r\n            }\r\n        }\r\n        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));\r\n        mCurrLocationMarker = mMap.addMarker(markerOptions);\r\n        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));\r\n        mMap.animateCamera(CameraUpdateFactory.zoomTo(11));\r\n        if (mGoogleApiClient != null) {\r\n            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,\r\n                    this);\r\n        }\r\n    }\r\n    @Override\r\n    public void onConnectionFailed(ConnectionResult connectionResult) {\r\n    }\r\n    public boolean checkLocationPermission() {\r\n        if (ContextCompat.checkSelfPermission(this,\r\n                Manifest.permission.ACCESS_FINE_LOCATION)\r\n                != PackageManager.PERMISSION_GRANTED) {\r\n\r\n            if (ActivityCompat.shouldShowRequestPermissionRationale(this,\r\n                    Manifest.permission.ACCESS_FINE_LOCATION)) {\r\n                ActivityCompat.requestPermissions(this,\r\n                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},\r\n                        MY_PERMISSIONS_REQUEST_LOCATION);\r\n            } else {\r\n                ActivityCompat.requestPermissions(this,\r\n                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},\r\n                        MY_PERMISSIONS_REQUEST_LOCATION);\r\n            }\r\n            return false;\r\n        } else {\r\n            return true;\r\n        }\r\n    }\r\n    @Override\r\n    public void onRequestPermissionsResult(int requestCode,\r\n                                           String permissions[], int[] grantResults) {\r\n        switch (requestCode) {\r\n            case MY_PERMISSIONS_REQUEST_LOCATION: {\r\n                if (grantResults.length &gt; 0\r\n                        &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) {\r\n                    if (ContextCompat.checkSelfPermission(this,\r\n                            Manifest.permission.ACCESS_FINE_LOCATION)\r\n                            == PackageManager.PERMISSION_GRANTED) {\r\n                        if (mGoogleApiClient == null) {\r\n                            buildGoogleApiClient();\r\n                        }\r\n                        mMap.setMyLocationEnabled(true);\r\n                    }\r\n                } else {\r\n                    Toast.makeText(this, \"permission denied\",\r\n                            Toast.LENGTH_LONG).show();\r\n                }\r\n                return;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>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.<\/p>\n<hr \/>\n<h4><strong>Google Map Example To Draw A Route Between Two Locations In Android Studio:<\/strong><\/h4>\n<p>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.<\/p>\n<p>AsyncTask is used to perform long running operations and show its result on the UI thread.<\/p>\n<p>Below you can download code, see final output and step by step explanation of example:<\/p>\n<p style=\"text-align: center;\"><a class=\"download\" href=\"http:\/\/www.mediafire.com\/file\/8p84zqyh5negfpd\/MapRouteExample.zip\/file\" target=\"_blank\" rel=\"nofollow noopener\">Download Code<\/a><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-884\" src=\"\/programming\/wp-content\/uploads\/2018\/03\/Google-Map-Draw-Route-Layout-Example.gif\" alt=\"Google Map Draw Route Layout Example\" width=\"256\" height=\"434\" \/><\/p>\n<p><strong>Step 1:<\/strong>\u00a0Create a new project\u00a0and name It MapExample.<\/p>\n<p><strong>Step 2:<\/strong>\u00a0Open Gradle Scripts &gt; build.gradle and add Retrofit and RecyclerView\u00a0Library dependency in it.<\/p>\n<pre>apply plugin: 'com.android.application'\r\n\r\nandroid {\r\n    compileSdkVersion 23\r\n    buildToolsVersion \"23.0.2\"\r\n\r\n    defaultConfig {\r\n        applicationId \"com.abhiandroid.MapRouteExample\"\r\n        minSdkVersion 15\r\n        targetSdkVersion 23\r\n        versionCode 1\r\n        versionName \"1.0\"\r\n    }\r\n    buildTypes {\r\n        release {\r\n            minifyEnabled false\r\n            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r\n        }\r\n    }\r\n}\r\n\r\ndependencies {\r\n    compile fileTree(dir: 'libs', include: ['*.jar'])\r\n    testCompile 'junit:junit:4.12'\r\n    compile 'com.android.support:appcompat-v7:23.1.1'\r\n    compile 'com.android.support:design:23.1.1'\r\n    compile 'com.google.android.gms:play-services:7.8.0'\r\n}<\/pre>\n<p><strong>Step 3:<\/strong>\u00a0Add Internet Permission in the AndroidManifest.xml:<\/p>\n<p>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.<\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;manifest xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    package=\"com.abhiandroid.MapRouteExample\"&gt;\r\n\r\n\r\n    &lt;uses-permission android:name=\"android.permission.INTERNET\" \/&gt;\r\n    &lt;uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" \/&gt;\r\n    &lt;uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\" \/&gt;\r\n    &lt;uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\" \/&gt;\r\n\r\n\r\n    &lt;application\r\n        android:allowBackup=\"true\"\r\n        android:icon=\"@mipmap\/ic_launcher\"\r\n        android:label=\"@string\/app_name\"\r\n        android:supportsRtl=\"true\"\r\n        android:theme=\"@style\/AppTheme\"&gt;\r\n        &lt;activity\r\n            android:name=\"com.abhiandroid.MapRouteExample.MainActivity\"\r\n            android:label=\"@string\/app_name\"\r\n            android:theme=\"@style\/AppTheme.NoActionBar\"&gt;\r\n            &lt;intent-filter&gt;\r\n                &lt;action android:name=\"android.intent.action.MAIN\" \/&gt;\r\n\r\n                &lt;category android:name=\"android.intent.category.LAUNCHER\" \/&gt;\r\n            &lt;\/intent-filter&gt;\r\n        &lt;\/activity&gt;\r\n\r\n        &lt;meta-data\r\n            android:name=\"com.google.android.maps.v2.API_KEY\"\r\n            android:value=\"AIzaSyDagu1__IQVkCjlGIGYkbdUf-JcJ0hofZ0\" \/&gt;\r\n\r\n        &lt;meta-data\r\n            android:name=\"com.google.android.gms.version\"\r\n            android:value=\"@integer\/google_play_services_version\" \/&gt;\r\n\r\n    &lt;\/application&gt;\r\n\r\n&lt;\/manifest&gt;<\/pre>\n<p><strong>Step 4:<\/strong>\u00a0Open res -&gt; layout -&gt; <strong>activity_main.xml (or) main.xml<\/strong> and add following code:<\/p>\n<p>In this step we create a support fragment in our\u00a0XML\u00a0file.<\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;RelativeLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    xmlns:app=\"http:\/\/schemas.android.com\/apk\/res-auto\"\r\n    xmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\n    android:layout_width=\"match_parent\"\r\n    android:layout_height=\"match_parent\"\r\n    app:layout_behavior=\"@string\/appbar_scrolling_view_behavior\"\r\n    tools:context=\"com.abhiandroid.MapRouteExample.MainActivity\"\r\n    tools:showIn=\"@layout\/activity_main\"&gt;\r\n\r\n    &lt;fragment\r\n        android:id=\"@+id\/map\"\r\n        android:name=\"com.google.android.gms.maps.SupportMapFragment\"\r\n        android:layout_width=\"match_parent\"\r\n        android:layout_gravity=\"center\"\r\n        android:layout_height=\"match_parent\"\r\n        \/&gt;\r\n\r\n&lt;\/RelativeLayout&gt;<\/pre>\n<p><strong>Step 5:<\/strong>\u00a0Create a new class DirectionsJSONParser.java in which we have parse method to parse the data which we get from direction API.<\/p>\n<pre>package com.abhiandroid.MapRouteExample;\r\n\r\nimport com.google.android.gms.maps.model.LatLng;\r\n\r\nimport org.json.JSONArray;\r\nimport org.json.JSONException;\r\nimport org.json.JSONObject;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.HashMap;\r\nimport java.util.List;\r\n\r\npublic class DirectionsJSONParser {\r\n\r\n    \/** Receives a JSONObject and returns a list of lists containing latitude and longitude *\/\r\n    public List&lt;List&lt;HashMap&lt;String,String&gt;&gt;&gt; parse(JSONObject jObject){\r\n\r\n        List&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt; routes = new ArrayList&lt;List&lt;HashMap&lt;String,String&gt;&gt;&gt;() ;\r\n        JSONArray jRoutes = null;\r\n        JSONArray jLegs = null;\r\n        JSONArray jSteps = null;\r\n\r\n        try {\r\n\r\n            jRoutes = jObject.getJSONArray(\"routes\");\r\n\r\n            \/** Traversing all routes *\/\r\n            for(int i=0;i&lt;jRoutes.length();i++){\r\n                jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray(\"legs\");\r\n                List path = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();\r\n\r\n                \/** Traversing all legs *\/\r\n                for(int j=0;j&lt;jLegs.length();j++){\r\n                    jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray(\"steps\");\r\n\r\n                    \/** Traversing all steps *\/\r\n                    for(int k=0;k&lt;jSteps.length();k++){\r\n                        String polyline = \"\";\r\n                        polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get(\"polyline\")).get(\"points\");\r\n                        List list = decodePoly(polyline);\r\n\r\n                        \/** Traversing all points *\/\r\n                        for(int l=0;l &lt;list.size();l++){\r\n                            HashMap&lt;String, String&gt; hm = new HashMap&lt;String, String&gt;();\r\n                            hm.put(\"lat\", Double.toString(((LatLng)list.get(l)).latitude) );\r\n                            hm.put(\"lng\", Double.toString(((LatLng)list.get(l)).longitude) );\r\n                            path.add(hm);\r\n                        }\r\n                    }\r\n                    routes.add(path);\r\n                }\r\n            }\r\n\r\n        } catch (JSONException e) {\r\n            e.printStackTrace();\r\n        }catch (Exception e){\r\n        }\r\n\r\n        return routes;\r\n    }\r\n    \r\n    private List decodePoly(String encoded) {\r\n\r\n        List poly = new ArrayList();\r\n        int index = 0, len = encoded.length();\r\n        int lat = 0, lng = 0;\r\n\r\n        while (index &lt; len) {\r\n            int b, shift = 0, result = 0;\r\n            do {\r\n                b = encoded.charAt(index++) - 63;\r\n                result |= (b &amp; 0x1f) &lt;&lt; shift;\r\n                shift += 5;\r\n            } while (b &gt;= 0x20);\r\n            int dlat = ((result &amp; 1) != 0 ? ~(result &gt;&gt; 1) : (result &gt;&gt; 1));\r\n            lat += dlat;\r\n\r\n            shift = 0;\r\n            result = 0;\r\n            do {\r\n                b = encoded.charAt(index++) - 63;\r\n                result |= (b &amp; 0x1f) &lt;&lt; shift;\r\n                shift += 5;\r\n            } while (b &gt;= 0x20);\r\n            int dlng = ((result &amp; 1) != 0 ? ~(result &gt;&gt; 1) : (result &gt;&gt; 1));\r\n            lng += dlng;\r\n\r\n            LatLng p = new LatLng((((double) lat \/ 1E5)),\r\n                    (((double) lng \/ 1E5)));\r\n            poly.add(p);\r\n        }\r\n\r\n        return poly;\r\n    }\r\n}<\/pre>\n<p><strong>Step 6:<\/strong>\u00a0Now open app -&gt; java -&gt; package -&gt; MainActivity.java and add the below code.<\/p>\n<p>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\u00a0 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.<\/p>\n<pre>package com.abhiandroid.MapRouteExample;\r\n\r\nimport android.app.ProgressDialog;\r\nimport android.graphics.Color;\r\nimport android.os.AsyncTask;\r\nimport android.os.Bundle;\r\nimport android.support.v7.app.AppCompatActivity;\r\nimport android.util.Log;\r\nimport android.view.Menu;\r\nimport android.view.MenuItem;\r\n\r\nimport com.google.android.gms.maps.CameraUpdateFactory;\r\nimport com.google.android.gms.maps.GoogleMap;\r\nimport com.google.android.gms.maps.OnMapReadyCallback;\r\nimport com.google.android.gms.maps.SupportMapFragment;\r\nimport com.google.android.gms.maps.model.BitmapDescriptorFactory;\r\nimport com.google.android.gms.maps.model.LatLng;\r\nimport com.google.android.gms.maps.model.MarkerOptions;\r\nimport com.google.android.gms.maps.model.PolylineOptions;\r\n\r\nimport org.json.JSONObject;\r\n\r\nimport java.io.BufferedReader;\r\nimport java.io.IOException;\r\nimport java.io.InputStream;\r\nimport java.io.InputStreamReader;\r\nimport java.net.HttpURLConnection;\r\nimport java.net.URL;\r\nimport java.util.ArrayList;\r\nimport java.util.HashMap;\r\nimport java.util.List;\r\n\r\n\r\npublic class MainActivity extends AppCompatActivity implements OnMapReadyCallback {\r\n\r\n    SupportMapFragment mapFragment;\r\n    GoogleMap mMap;\r\n    LatLng origin = new LatLng(30.739834, 76.782702);\r\n    LatLng dest = new LatLng(30.705493, 76.801256);\r\n    ProgressDialog progressDialog;\r\n    @Override\r\n    protected void onCreate(Bundle savedInstanceState) {\r\n        super.onCreate(savedInstanceState);\r\n        setContentView(R.layout.activity_main);\r\n        mapFragment = (SupportMapFragment) getSupportFragmentManager()\r\n                .findFragmentById(R.id.map);\r\n        mapFragment.getMapAsync(this);\r\n        drawPolylines();\r\n\r\n    }\r\n\r\n    private void drawPolylines() {\r\n        progressDialog = new ProgressDialog(MainActivity.this);\r\n        progressDialog.setMessage(\"Please Wait, Polyline between two locations is building.\");\r\n        progressDialog.setCancelable(false);\r\n        progressDialog.show();\r\n\r\n        \/\/ Checks, whether start and end locations are captured\r\n        \/\/ Getting URL to the Google Directions API\r\n        String url = getDirectionsUrl(origin, dest);\r\n        Log.d(\"url\", url + \"\");\r\n        DownloadTask downloadTask = new DownloadTask();\r\n        \/\/ Start downloading json data from Google Directions API\r\n        downloadTask.execute(url);\r\n    }\r\n    @Override\r\n    public boolean onCreateOptionsMenu(Menu menu) {\r\n        \/\/ Inflate the menu; this adds items to the action bar if it is present.\r\n        getMenuInflater().inflate(R.menu.menu_main, menu);\r\n        return true;\r\n    }\r\n\r\n    @Override\r\n    public boolean onOptionsItemSelected(MenuItem item) {\r\n        \/\/ Handle action bar item clicks here. The action bar will\r\n        \/\/ automatically handle clicks on the Home\/Up button, so long\r\n        \/\/ as you specify a parent activity in AndroidManifest.xml.\r\n        int id = item.getItemId();\r\n\r\n        \/\/noinspection SimplifiableIfStatement\r\n        if (id == R.id.action_settings) {\r\n            return true;\r\n        }\r\n\r\n        return super.onOptionsItemSelected(item);\r\n    }\r\n\r\n    @Override\r\n    public void onMapReady(GoogleMap googleMap) {\r\n        mMap = googleMap;\r\n        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);\r\n      googleMap.addMarker(new MarkerOptions()\r\n              .position(origin)\r\n              .title(\"LinkedIn\")\r\n              .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));\r\n\r\n        googleMap.addMarker(new MarkerOptions()\r\n                .position(dest));\r\n\r\n        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(origin, 15));\r\n\r\n    }\r\n\r\n\r\n    private class DownloadTask extends AsyncTask&lt;String, Void, String&gt; {\r\n\r\n        @Override\r\n        protected String doInBackground(String... url) {\r\n\r\n            String data = \"\";\r\n\r\n            try {\r\n                data = downloadUrl(url[0]);\r\n            } catch (Exception e) {\r\n                Log.d(\"Background Task\", e.toString());\r\n            }\r\n            return data;\r\n        }\r\n\r\n        @Override\r\n        protected void onPostExecute(String result) {\r\n            super.onPostExecute(result);\r\n\r\n            ParserTask parserTask = new ParserTask();\r\n\r\n\r\n            parserTask.execute(result);\r\n\r\n        }\r\n    }\r\n\r\n\r\n    \/**\r\n     * A class to parse the Google Places in JSON format\r\n     *\/\r\n    private class ParserTask extends AsyncTask&lt;String, Integer, List&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt;&gt; {\r\n\r\n        \/\/ Parsing the data in non-ui thread\r\n        @Override\r\n        protected List&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt; doInBackground(String... jsonData) {\r\n\r\n            JSONObject jObject;\r\n            List&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt; routes = null;\r\n\r\n            try {\r\n                jObject = new JSONObject(jsonData[0]);\r\n                DirectionsJSONParser parser = new DirectionsJSONParser();\r\n\r\n                routes = parser.parse(jObject);\r\n            } catch (Exception e) {\r\n                e.printStackTrace();\r\n            }\r\n            return routes;\r\n        }\r\n\r\n        @Override\r\n        protected void onPostExecute(List&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt; result) {\r\n\r\n            progressDialog.dismiss();\r\n            Log.d(\"result\", result.toString());\r\n            ArrayList points = null;\r\n            PolylineOptions lineOptions = null;\r\n\r\n            for (int i = 0; i &lt; result.size(); i++) {\r\n                points = new ArrayList();\r\n                lineOptions = new PolylineOptions();\r\n\r\n                List&lt;HashMap&lt;String, String&gt;&gt; path = result.get(i);\r\n\r\n                for (int j = 0; j &lt; path.size(); j++) {\r\n                    HashMap&lt;String, String&gt; point = path.get(j);\r\n\r\n                    double lat = Double.parseDouble(point.get(\"lat\"));\r\n                    double lng = Double.parseDouble(point.get(\"lng\"));\r\n                    LatLng position = new LatLng(lat, lng);\r\n\r\n                    points.add(position);\r\n                }\r\n\r\n                lineOptions.addAll(points);\r\n                lineOptions.width(12);\r\n                lineOptions.color(Color.RED);\r\n                lineOptions.geodesic(true);\r\n\r\n            }\r\n\r\n\/\/ Drawing polyline in the Google Map for the i-th route\r\n            mMap.addPolyline(lineOptions);\r\n        }\r\n    }\r\n\r\n    private String getDirectionsUrl(LatLng origin, LatLng dest) {\r\n\r\n        \/\/ Origin of route\r\n        String str_origin = \"origin=\" + origin.latitude + \",\" + origin.longitude;\r\n\r\n        \/\/ Destination of route\r\n        String str_dest = \"destination=\" + dest.latitude + \",\" + dest.longitude;\r\n\r\n        \/\/ Sensor enabled\r\n        String sensor = \"sensor=false\";\r\n        String mode = \"mode=driving\";\r\n        \/\/ Building the parameters to the web service\r\n        String parameters = str_origin + \"&amp;\" + str_dest + \"&amp;\" + sensor + \"&amp;\" + mode;\r\n\r\n        \/\/ Output format\r\n        String output = \"json\";\r\n\r\n        \/\/ Building the url to the web service\r\n        String url = \"https:\/\/maps.googleapis.com\/maps\/api\/directions\/\" + output + \"?\" + parameters;\r\n\r\n\r\n        return url;\r\n    }\r\n\r\n    \/**\r\n     * A method to download json data from url\r\n     *\/\r\n    private String downloadUrl(String strUrl) throws IOException {\r\n        String data = \"\";\r\n        InputStream iStream = null;\r\n        HttpURLConnection urlConnection = null;\r\n        try {\r\n            URL url = new URL(strUrl);\r\n\r\n            urlConnection = (HttpURLConnection) url.openConnection();\r\n\r\n            urlConnection.connect();\r\n\r\n            iStream = urlConnection.getInputStream();\r\n\r\n            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));\r\n\r\n            StringBuffer sb = new StringBuffer();\r\n\r\n            String line = \"\";\r\n            while ((line = br.readLine()) != null) {\r\n                sb.append(line);\r\n            }\r\n\r\n            data = sb.toString();\r\n\r\n            br.close();\r\n            Log.d(\"data\", data);\r\n\r\n        } catch (Exception e) {\r\n            Log.d(\"Exception\", e.toString());\r\n        } finally {\r\n            iStream.close();\r\n            urlConnection.disconnect();\r\n        }\r\n        return data;\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>Now run the App. If you are connected to internet and provide access to your location then in Map you will see route layout draws in Map.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Android allows us to integrate Google Maps in our application. For this Google provides us a library via Google Play Services for using maps.\u00a0In order to use the Google Maps API, you must register your application on the\u00a0Google Developer Console\u00a0and enable the API. Steps For Getting The Google Maps Api Key: An API key is &hellip; <a href=\"https:\/\/abhiandroid.com\/programming\/googlemaps\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Google Maps Tutorial With Example In Android Studio [Step by Step]<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"open","ping_status":"closed","template":"home.php","meta":{"footnotes":""},"class_list":["post-781","page","type-page","status-publish","hentry"],"psp_head":"<title>Google Maps Tutorial With Example In Android Studio [Step by Step] \u2013 Abhi Android<\/title>\r\n<meta name=\"description\" content=\"Learn how to integrate Google Maps in your Android App. We explain everything step by step using two examples in Android Studio.\" \/>\r\n<meta name=\"robots\" content=\"index,follow\" \/>\r\n<link rel=\"canonical\" href=\"https:\/\/abhiandroid.com\/programming\/googlemaps\" \/>\r\n","_links":{"self":[{"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/pages\/781","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/comments?post=781"}],"version-history":[{"count":4,"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/pages\/781\/revisions"}],"predecessor-version":[{"id":990,"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/pages\/781\/revisions\/990"}],"wp:attachment":[{"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/media?parent=781"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}