Integrate google map in android tutorial

Udemy Generic 728x90

Objective

In this tutorial our objective is to integrate google map in android application.

 

Google Maps is a web mapping service developed by Google. It offers satellite imagery, panoramic views of streets public transportation and many more features. In this article, I am going to explain the integration process of google maps and show user’s current location on the map

Step 2

Create map project

  1. Let’s start with creating a new project on android studio. File => New => New Project. Give Application name and then Next. Then select the form factor your app will run on like minimum sdk, here I am using API 15 (Android 4.0.3 – ice cream sandwich).  Then click Next. 
  2. Now choose Google Maps Activity. Then click Next. Then start building application. If you don’t have google map activity. Then you have to upgrade your Android Sdk and may be also your android studio. For this you can direct download form developer.android.com or follow stackoverflow.
  3. When you add google activity, please check in build.gradle(Module:app) file, if following dependency is imported or not. if not, then add this in dependencies and re-build your application.

    <br />
    compile 'com.google.android.gms:play-services:8.3.0'<br />
    

 

Step 3

Integrate google map in activity

  1. After building the application, open google_maps_api.xml file present in your layouts folder. This file got created automatically, when we choose google_map_activity as our default activity. Here you have to enter the google maps key, for this you have to call console developer url like  https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=47:D3:38:E7:93:D4:3D:C7:25:B8:E6:BA:9A:C7:2C:FC:E1:B0:ED:DF%3Bcom.numetriclabz.gpsmaptracker. 
    This url is different for every application and you’ll get the url in your google_maps_api.xml file in comments.
  2. After calling this url you have to create the project in developer console. specify the location. and get the google maps key, it will be like AIzaxxxxxxxxxxx-xxxxxxxxxxxxx.

    </p>
    <p>    &lt;!--<br />
        TODO: Before you run your application, you need a Google Maps API key.</p>
    <p>    To get one, follow this link, follow the directions and press &quot;Create&quot; at the end:</p>
    <p>    https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&amp;keyType=CLIENT_SIDE_ANDROID&amp;r=47:D3:38:E7:93:D4:3D:C7:25:B8:E6:BA:9A:C7:2C:FC:E1:B0:ED:DF%3Bcom.numetriclabz.gpsmaptracker</p>
    <p>    You can also add your credentials to an existing key, using this line:<br />
        47:D3:38:E7:93:D4:3D:C7:25:B8:E6:BA:9A:C7:2C:FC:E1:B0:ED:DF;com.numetriclabz.gpsmaptracker</p>
    <p>    Alternatively, follow the directions here:<br />
    
    https://developers.google.com/maps/documentation/android/start#get-key</p>
    
    <p>    Once you have your key (it starts with &quot;AIza&quot;), replace the &quot;google_maps_key&quot;<br />
        string in this file.<br />
        --&gt;<br />
        &lt;string name=&quot;google_maps_key&quot; templateMergeStrategy=&quot;preserve&quot; translatable=&quot;false&quot;&gt;YOUR_API_KEY&lt;/string&gt;</p>
    <p>

  3. Now build your app and  run it either in your phone or android emulator If the execution is successful then it will show the world map at home page. You can see map marker is focused on the sydney because it is set as default.

 

Step 4

Add current location

  1. Now in this step we are going to set up our location in google map. First we have to check that our app must app have the required permission.
  2. So, open your AndroidManifest.xml file and add the following code their. 

    <br />
        &lt;!--to access internet--&gt;<br />
        &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;<br />
        &lt;!--to access information about networks--&gt;<br />
        &lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot;/&gt;<br />
        &lt;!--to access approximate location through network location providers--&gt;<br />
        &lt;uses-permission android:name=&quot;android.permission.ACCESS_COARSE_LOCATION&quot;/&gt;<br />
        &lt;!--to get precise location through GPS location provider--&gt;<br />
        &lt;uses-permission android:name=&quot;android.permission.ACCESS_FINE_LOCATION&quot; /&gt;<br />
    

  3. Now open MainActivity.java file and in onMapReady() method set mMap.setMyLocationEnabled(true), it will show your current location in map. But before this you have to check that if user is already enabled the GPS or not . You can do this with isMyLocationEnabled(). 

<br />
    /**<br />
     * Manipulates the map once available.<br />
     * This callback is triggered when the map is ready to be used.<br />
     * This is where we can add markers or lines, add listeners or move the camera. In this case,<br />
     * we just add a marker near Sydney, Australia.<br />
     * If Google Play services is not installed on the device, the user will be prompted to install<br />
     * it inside the SupportMapFragment. This method will only be triggered once the user has<br />
     * installed Google Play services and returned to the app.<br />
     */<br />
    public void onMapReady(GoogleMap googleMap) {<br />
        mMap = googleMap;<br />
        if(mMap.isMyLocationEnabled()){<br />
            mMap.setMyLocationEnabled(true);<br />
        }<br />
        else {<br />
            showSettingsAlert();<br />
        }<br />
    }<br />

<br />
    /**<br />
     * Function to show settings alert dialog<br />
     * On pressing Settings button will lauch Settings Options<br />
     */<br />
    public void showSettingsAlert(){<br />
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);</p>
<p>        // Setting Dialog Title<br />
        alertDialog.setTitle(&quot;GPS is settings&quot;);</p>
<p>        // Setting Dialog Message<br />
        alertDialog.setMessage(&quot;GPS is not enabled. Do you want to go to settings menu?&quot;);</p>
<p>        // On pressing Settings button<br />
        alertDialog.setPositiveButton(&quot;Settings&quot;, new DialogInterface.OnClickListener() {<br />
            public void onClick(DialogInterface dialog,int which) {<br />
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);<br />
                startActivity(intent);<br />
            }<br />
        });</p>
<p>        // on pressing cancel button<br />
        alertDialog.setNegativeButton(&quot;Cancel&quot;, new DialogInterface.OnClickListener() {<br />
            public void onClick(DialogInterface dialog, int which) {<br />
                dialog.cancel();<br />
            }<br />
        });</p>
<p>        // Showing Alert Message<br />
        alertDialog.show();<br />
    }<br />
}<br />

Map-With-Current-location

 

Step 5

Required files:

MapsActivity.java

<br />
package com.numetriclabz.gpsmaptracker;</p>
<p>import android.app.AlertDialog;<br />
import android.content.DialogInterface;<br />
import android.content.Intent;<br />
import android.location.Address;<br />
import android.location.Geocoder;<br />
import android.provider.Settings;<br />
import android.support.v4.app.FragmentActivity;<br />
import android.os.Bundle;<br />
import android.view.View;<br />
import android.widget.EditText;</p>
<p>import com.google.android.gms.maps.CameraUpdateFactory;<br />
import com.google.android.gms.maps.GoogleMap;<br />
import com.google.android.gms.maps.OnMapReadyCallback;<br />
import com.google.android.gms.maps.SupportMapFragment;<br />
import com.google.android.gms.maps.model.LatLng;<br />
import com.google.android.gms.maps.model.MarkerOptions;</p>
<p>import java.io.IOException;<br />
import java.util.List;</p>
<p>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {</p>
<p>    private GoogleMap mMap;</p>
<p>    @Override<br />
    protected void onCreate(Bundle savedInstanceState) {<br />
        super.onCreate(savedInstanceState);<br />
        setContentView(R.layout.activity_maps);<br />
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.<br />
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()<br />
                .findFragmentById(R.id.map);<br />
        mapFragment.getMapAsync(this);<br />
    }</p>
<p>    /**<br />
     * Manipulates the map once available.<br />
     * This callback is triggered when the map is ready to be used.<br />
     * This is where we can add markers or lines, add listeners or move the camera. In this case,<br />
     * we just add a marker near Sydney, Australia.<br />
     * If Google Play services is not installed on the device, the user will be prompted to install<br />
     * it inside the SupportMapFragment. This method will only be triggered once the user has<br />
     * installed Google Play services and returned to the app.<br />
     */<br />
    @Override<br />
    public void onMapReady(GoogleMap googleMap) {<br />
        mMap = googleMap;</p>
<p>        // Add a marker in Sydney and move the camera<br />
        LatLng sydney = new LatLng(-34, 151);<br />
        mMap.addMarker(new MarkerOptions().position(sydney).title(&quot;Sydney&quot;));<br />
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));</p>
<p>        if(mMap.isMyLocationEnabled()){<br />
            mMap.setMyLocationEnabled(true);<br />
        }<br />
        else {<br />
            showSettingsAlert();<br />
        }<br />
    }</p>
<p>    /**<br />
     * Function to show settings alert dialog<br />
     * On pressing Settings button will lauch Settings Options<br />
     * */<br />
    public void showSettingsAlert(){<br />
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);</p>
<p>        // Setting Dialog Title<br />
        alertDialog.setTitle(&quot;GPS is settings&quot;);</p>
<p>        // Setting Dialog Message<br />
        alertDialog.setMessage(&quot;GPS is not enabled. Do you want to go to settings menu?&quot;);</p>
<p>        // On pressing Settings button<br />
        alertDialog.setPositiveButton(&quot;Settings&quot;, new DialogInterface.OnClickListener() {<br />
            public void onClick(DialogInterface dialog,int which) {<br />
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);<br />
                startActivity(intent);<br />
            }<br />
        });</p>
<p>        // on pressing cancel button<br />
        alertDialog.setNegativeButton(&quot;Cancel&quot;, new DialogInterface.OnClickListener() {<br />
            public void onClick(DialogInterface dialog, int which) {<br />
                dialog.cancel();<br />
            }<br />
        });</p>
<p>        // Showing Alert Message<br />
        alertDialog.show();<br />
    }<br />
}<br />

Activity_maps.xml

<br />
&lt;fragment xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br />
    xmlns:map=&quot;http://schemas.android.com/apk/res-auto&quot;<br />
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br />
    android:id=&quot;@+id/map&quot;<br />
    android:name=&quot;com.google.android.gms.maps.SupportMapFragment&quot;<br />
    android:layout_width=&quot;match_parent&quot;<br />
    android:layout_height=&quot;389dp&quot;<br />
    tools:context=&quot;com.numetriclabz.gpsmaptracker.MapsActivity&quot; /&gt;<br />

 

AndroidManifest.xml

<br />
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br />
&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br />
    package=&quot;com.numetriclabz.gpsmaptracker&quot;&gt;</p>
<p>    &lt;!--<br />
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use<br />
         Google Maps Android API v2, but you must specify either coarse or fine<br />
         location permissions for the 'MyLocation' functionality.<br />
    --&gt;<br />
        &lt;!--to access internet--&gt;<br />
        &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;<br />
        &lt;!--to access information about networks--&gt;<br />
        &lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot;/&gt;</p>
<p>        &lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot;/&gt;<br />
        &lt;uses-permission android:name=&quot;com.google.android.providers.gsf.permission.READ_GSERVICES&quot;/&gt;</p>
<p>        &lt;!--to access approximate location through network location providers--&gt;<br />
        &lt;uses-permission android:name=&quot;android.permission.ACCESS_COARSE_LOCATION&quot;/&gt;<br />
        &lt;!--to get precise location through GPS location provider--&gt;<br />
        &lt;uses-permission android:name=&quot;android.permission.ACCESS_FINE_LOCATION&quot; /&gt;</p>
<p>    &lt;application<br />
        android:allowBackup=&quot;true&quot;<br />
        android:icon=&quot;@mipmap/ic_launcher&quot;<br />
        android:label=&quot;@string/app_name&quot;<br />
        android:supportsRtl=&quot;true&quot;<br />
        android:theme=&quot;@style/AppTheme&quot;&gt;</p>
<p>        &lt;!--<br />
             The API key for Google Maps-based APIs is defined as a string resource.<br />
             (See the file &quot;res/values/google_maps_api.xml&quot;).<br />
             Note that the API key is linked to the encryption key used to sign the APK.<br />
             You need a different API key for each encryption key, including the release key that is used to<br />
             sign the APK for publishing.<br />
             You can define the keys for the debug and release targets in src/debug/ and src/release/.<br />
        --&gt;<br />
        &lt;meta-data<br />
            android:name=&quot;com.google.android.geo.API_KEY&quot;<br />
            android:value=&quot;@string/google_maps_key&quot; /&gt;</p>
<p>        &lt;activity<br />
            android:name=&quot;.MapsActivity&quot;<br />
            android:label=&quot;@string/title_activity_maps&quot;&gt;<br />
            &lt;intent-filter&gt;<br />
                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;</p>
<p>                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;<br />
            &lt;/intent-filter&gt;<br />
        &lt;/activity&gt;<br />
    &lt;/application&gt;<br />
&lt;/manifest&gt;<br />

Udemy Generic 728x90

Spread the word. Share this post!

  • fiqky

    mantap but i want to make imagebutton for showing current location ?

  • Frans Appel

    Very nice, but with one ommission:

    mMap.isMyLocationEnabled()
    isn’t working very well.