Android Google Maps Tutorial with Example

By Android Google Maps Tutorial with Example

Hi, and welcome to yet another Android Tutorial. In this article, I will be tackling Android Google Map. Android enables us to integrate Google map into our android applications. With Google Map you can display directions, search places and calculate distance between point A and B. Actually you can customize Google map in your application according to your requirement. There are four types of Google Maps: Normal, Hybrid, Satellite and Terrain. You also have an option to no map.

  • Normal Map: This displays a typical map with natural features like rivers, as well as some man-made features. googleMap.setMapType (GoogleMap.MAP_TYPE_NORMAL); 
  • Hybrid Map: This displays satellite photograph data. It also displays roads and feature labels. googleMap.setMapType (GoogleMap.MAP_TYPE_HYBRID);
  • Satellite Map: This displays satelliete photograph data except roads and feature labels. googleMap.setMapType (GoogleMap. MAP_TYPE_SATELLITE);  
  • Terrain Map: This displays photographic dta and includes colors, contour lines and labels. googleMap.setMapType (GoogleMap.MAP_TYPE_TERRAIN);  
  • None: This displays and empty grid with no tiles loaded in it.

Google Map Android Example

Now let us see how we create Google Map and integrate it into our app. To do this create a new project in Android Studio IDE and select Google Maps Activity.

 

Before you run your application, you need a Google Maps API key. To get one, follow the link inside google_map_api.xml, follow the directions and press "Create" at the end.

After successfully generating the Google Maps API key, copy the key in the google_map.xml file.

<string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">YOUR_KEY_HERE</string>

The following is the code of the activity_maps.xml

<?xml version="1.0" encoding="utf-8"?>
<fragment 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:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity" />

The next step is to get the Google Map in our application. To do so, we need to implement OnMapReadyCallback interface and override the onMapReady() callback method. The following is the code for MapsActivity.java.

package com.ericmuchenah.googlemapandroid;
import androidx.fragment.app.FragmentActivity;
import android.os.Bundle;
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 MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    private GoogleMap mMap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

Next step we need to add the required permissions in our application. We need permissions for Location and Internet. To do so, add the following lines in AndroidManifest.xml file.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

This will be the code for AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ericmuchenah.googlemapandroid">
    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality.
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <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">
        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />
        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

To finish integrating Google Map in our application, we need to add some dependencies in build.gradel file.

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'com.google.android.gms:play-services-maps:16.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}

Android Google Map Output

The following screenshot shows the output of the Google Map.

Conclusion

In this tutorial, we learnt how to use Google Maps in our Android apps. You can use this application to integrate Google Map into an app in minutes.

Thank you for reading this article. Please vote below and share it with your friends and fellow android developers.

Was this article helpful?
Donate with PayPal: https://www.paypal.com/donate

Bessy
Eric Murithi Muchenah

Life is beautiful, time is precious. Make the most out of it.