ZOFTINO.COM android and web dev tutorials

Android Google Maps Tutorial

Google maps can be integrated into your android application using Google maps Android API which is part of Google play services API. For that, you need to include Google play services client library in your project and use Google maps Android API to implement maps feature in your app.

On the android device, Google maps Android API in your app interacts with back ground service which is part of Google play service APK and runs on OS to provide maps feature. Android devices come with Google play service APK. If Google makes any change to Google play service APK, it will be automatically updated on user device via Google play store. So this way, you can use latest maps API in your app without needing to worry about whether the user devices support the feature or not as Google play store delivers latest Google play service APK as soon as it is available.

This post covers how to add Google play services API or library to your project, enable Google maps android API in developer console, add API key to project, use Google play services maps API to show maps in your app with an example, and shows using zoom, adding marker, custom marker, circle, ploylines, polygon, info window and ground overlay to map.

Before you continue with this example, you may want to learn android and latest features with examples. Please visit android tutorials for all android concepts, components and libraries with examples which uses latest components and API.

Google Play Services SDK in Android Studio

Google Play Services SDK needs to be installed in Android Studio so that you can add to your project the library related to Google maps API. So, the first step in using Google maps Android API is to make sure that Google play service SDK is installed in android studio by opening Android SDK window and checking Google Repository under Support Repository as shown in the screen shot below. You can open Android SDK window by going to Tools > Android > SDK Manager > SDK Tools.

android studio google play service sdk

Adding Google maps Android API or Library to Your Project

You can add play services library which contains all Google play service APIs to your project. But, it is better to use selective API libraries so that method limitation issue will not come into picture.

Since we are going to use Google maps Android API in this example project, we will add play-services-maps to build. gradle file.

 dependencies {
    . . .

    implementation 'com.google.android.gms:play-services-maps:11.4.2'
} 

Enabling Google Maps Android API in Developers Console

To use Google maps android API in your android app, you need to enable google maps API for your project. To do that, first go to Google developer console at https://console.developers.google.com/apis/, login using your Google account, create a project by clicking create project button, then click enable APIs and services link, click Google maps android api and click enable. Below screen shot shows Google developers console dashboard where you can see create project button and enable APIs and services link.

google developer console enable google map api

After enabling the API, you need to create credentials. To create credentials, click credentials link in the left navigation on the Google developer console dashboard (above screen) and then click create credentials button. Copy the key to add it to your android project.

Adding API Key to Android Project

Once you followed above instructions to enable API and create API key, copy the key and add it to your android project’s manifest file by adding meta-data element as child of application element. The meta-data element name attribute should be com.google.android.geo.API_KEY and value is the key as shown below.

And also, you need to add Google play services version to android manifest file using meta-data tag with name as com.google.android.gms.version and value as version as shown below.

Google play services add the required permissions such as android.permission.INTERNET and android.permission.ACCESS_NETWORK_STATE. But if your app needs other permissions, you have to add them to manifest file, for example location permission.

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="zoftino.com.googleplayservices">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
	<meta-data
    		android:name="com.google.android.gms.version"
    		android:value="@integer/google_play_services_version" />

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="dummmmmmyyyyyykeeeeeyyyyyyy"/>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".GoogleMapActivity"></activity>
    </application>
 

Android Google Maps Example

After setup described aboved is done, you can use Google maps android API in your application. First you need to add com.google.android.gms.maps.SupportMapFragment fragment to layout. Then create map activity which implements OnMapReadyCallback interface. The interface has one method onMapReady in which you can configure GoogleMap object. In onCreate method of the activity, add map-ready-callback to map fragment.

Below example displays Google maps with a marker which identifies a location.

Layout

 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    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"
    tools:context=".GoogleMapActivity">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/g_map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toolbar"/>
</android.support.constraint.ConstraintLayout> 

Activity

 import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class GoogleMapActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.google_maps_layout);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.g_map);
        mapFragment.getMapAsync(this);
    }
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        //seattle coordinates
        LatLng seattle = new LatLng(47.6062095, -122.3320708);
        mMap.addMarker(new MarkerOptions().position(seattle).title("Seattle"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(seattle));
    }
}

Android Google Maps Example Output

Google maps android api example

Android Google Maps Testing

To test your app that uses Google play services API, you can use emulator or device with any of recent versions of android and Google play store.

Android Google Maps Zoom

You can set minimum and maximum zoom on GoogleMap object by calling setMinZoomPreference and setMaxZoomPreference methods.

mMap.setMinZoomPreference(5);
mMap.setMaxZoomPreference(20); 
android google maps api zoom example

Android Google Maps Circle

Circle can be added to map by creating CircleOptions object and setting various configuration such as radius, fill color, stroke and latitude and longitude coordinate etc as shown below.

android google maps api circle example
 public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    
    mMap.setMinZoomPreference(9);
    
    LatLng seattle = new LatLng(47.6062095, -122.3320708);

    CircleOptions circleOptions = new CircleOptions();
    circleOptions.center(seattle);
    circleOptions.radius(8500);
    circleOptions.fillColor(Color.BLUE);
    circleOptions.strokeColor(Color.RED);
    circleOptions.strokeWidth(4);

     mMap.addCircle(circleOptions);
     
    //seattle coordinates
     seattle = new LatLng(47.6062095, -122.3320708);
    mMap.addMarker(new MarkerOptions().position(seattle).title("Seattle"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(seattle));
} 

Android Google Maps Polyline

You can draw a line on map joining two or more locations. This is mainly used for showing routes or directions. To draw polyline on the map, you need to instantiate PolylineOptions object, add coordinates you want to join and set various options such as color, geodesic, startCap, endCap, width, and jointType etc. And add the PolylineOptions object to GoogleMap object by calling addPolyline method on it.

 mMap.setMinZoomPreference(11);

LatLng seattle = new LatLng(47.6062095, -122.3320708);
LatLng bellevue = new LatLng(47.6101497, -122.2015159);

PolylineOptions plo =  new PolylineOptions();
plo.add(seattle);
plo.add(bellevue);
plo.color(Color.RED);
plo.geodesic(true);
plo.startCap(new RoundCap());
plo.width(20);
plo.jointType(JointType.BEVEL);

mMap.addPolyline(plo);
 
android google maps api polyline example

Android Google Maps Polygon

You can add polygon shape by defining PolygonOptions and adding it to GoogleMap by calling addPolygon method on it as shown below and screen shot show polygon on map. Polygon shape is used to represent area on map.

 public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    mMap.setMinZoomPreference(10);

    LatLng issaquah = new LatLng(47.5301011, -122.0326191);
    LatLng seattle = new LatLng(47.6062095, -122.3320708);
    LatLng bellevue = new LatLng(47.6101497, -122.2015159);
    LatLng sammamish = new LatLng(47.6162683, -122.0355736);
    LatLng redmond = new LatLng(47.6739881, -122.121512);

    PolygonOptions polygonOptions = new PolygonOptions();
    polygonOptions.add(issaquah, seattle, bellevue, sammamish, redmond);
    polygonOptions.strokeJointType(JointType.ROUND);
    polygonOptions.strokeColor(Color.RED);
    polygonOptions.strokeWidth(10);

    mMap.addPolygon(polygonOptions);

    mMap.moveCamera(CameraUpdateFactory.newLatLng(redmond));
} 
android google maps api polygon example

Android Google Maps Custom Marker

You can customize marker using MarkerOptions by adding icon and setting other attributes as shown below.

 mMap.setMinZoomPreference(10);
LatLng bellevue = new LatLng(47.6101497, -122.2015159);

MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(new LatLng(47.6101497, -122.2015159))
        .title("Bellevue")
        .icon( BitmapDescriptorFactory.fromResource(R.drawable.computer))
        .rotation(20)
        .draggable(false);
mMap.addMarker(markerOptions);

mMap.moveCamera(CameraUpdateFactory.newLatLng(bellevue));
 
android google maps api custom marker example

Map Types

You can display different types of Google maps in your application by calling setMapType and passing map type such as MAP_TYPE_HYBRID, MAP_TYPE_NORMAL, MAP_TYPE_SATELLITE or MAP_TYPE_TERRAIN.

mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

Android Google Maps Ground Overlay

Ground overlay, which you can add to map, is an image tied to earth surface. The difference between marker and ground overlay is that marker is tied to screen and its orientation is not changed on rotating or tilting the map. Whereas ground overlay image changes its orientation on rotating or tilting the map.

Below screen shot shows google map in hybrid mode with ground overlay.

android google maps api ground overlay example
 mMap.setMinZoomPreference(10);
LatLng bellevue = new LatLng(47.6101497, -122.2015159);

GroundOverlayOptions groundOverlayOptions = new GroundOverlayOptions ();
groundOverlayOptions.position(bellevue, 100, 100 )
        .image( BitmapDescriptorFactory.fromResource(R.drawable.computer));

mMap.addGroundOverlay(groundOverlayOptions);
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

mMap.moveCamera(CameraUpdateFactory.newLatLng(bellevue)); 

If you have multiple images which cover large area, you can use tile overlay.

Android Google Maps Info Window

In response to touch events of marker, you can show info window and hide info window by calling hideInfoWindow and showInfoWindow methods on Marker object. By default, info window displays title added to MarkerOptions object.

 MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(bellevue)
        .title("Bellevue")
        .icon(BitmapDescriptorFactory.defaultMarker( BitmapDescriptorFactory.HUE_GREEN));

Marker m = mMap.addMarker(markerOptions);
m.showInfoWindow(); 
android google maps api info window example