Maps activity in android app

Hey Technoz, today we’ll see how to integrate Google maps in our android app. If you are using Android Studio, you can directly use ‘Google Maps Activity’ from file menu and it’ll generate a ready made MapsActivity. However, we’ll discuss whole tutorial Step by Step.

Integrate Map in android app

So, open Android Studio and start a new project using File->New->Google->Google Maps Activity. Let the gradle build finish and as a result, you’ll have one java file and two xml files. Here, the java file is MapsActivity.java as follows.

package net.softglobe.mapsapp;

import android.support.v4.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.BitmapDescriptorFactory;
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(20.385906, 78.126256);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Sydney"));
        // use following line for custom icon
        //mMap.addMarker(new MarkerOptions().position(sydney).title("Sydney").icon(BitmapDescriptorFactory.fromResource(R.drawable.map)));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

This file contains overridden function onMapReady which is responsible to add marker in the map. Here, we created the object of LatLng class-‘sydney’. ‘LatLng’ stand for Latitude and Longitude. The constructor takes parameters of latitude and longitude respectively and the marker is set according to the values. The addMarker() function adds the title and custom icon (optional). If it is not set, the api uses the default red mark icon.

The layout files will be create as follows.

<?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" />

Lets see google_maps_api.xml file in values directory as follows.

<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_SIDE_ANDROID&r=4E:55:4E:42:27:33:AD:A5:6B:5F:E9:F2:EB:5E:7E:50:AD:1D:7B:22%3Bnet.softglobe.arsoddynamic

    You can also add your credentials to an existing key, using these values:

    Package name:
    4E:55:4E:42:27:33:AD:A5:6B:5F:E9:F2:EB:5E:7E:50:AD:1D:7B:22

    SHA-1 certificate fingerprint:
    4E:55:4E:42:27:33:AD:A5:6B:5F:E9:F2:EB:5E:7E:50:AD:1D:7B:22

    Alternatively, follow the directions here:
    https://developers.google.com/maps/documentation/android/start#get-key

    Once you have your key (it starts with "AIza"), replace the "google_maps_key"
    string in this file.
    -->
    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">YOUR_KEY_HERE</string>
</resources>

Copy and paste the above url in browser, The system will redirect you to the Google API’s page as shown below.

maps activity in android

Click Continue, and as a result, it will generate new api key for your app as shown below.

maps activity in android

Copy this key and paste it in above file as a string value.

Lastly, add following permissions in your AndroidManifest.xml files as follows. I have pasted Whole file for clarification.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.softglobe.mapsapp">

    <!-- adding internet permission -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />

    <!--
         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_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppThemeNew">
        <activity
            android:name=".MapsActivity"
            android:theme="@style/AppTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!--
             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" />
    </application>

</manifest>

So, launch the app on emulator or real device, Lets see the map on screen with a red marker on map in below image.

maps activity in android

Obviously, We need the device which have Google Play Services installed see a map. Otherwise, the api will tell the user to update it.

Download Source Code

If you have any problems implementing the above code, then feel free comment below. We’ll try our best to solve your query. Alternatively, You can download the source code from below link.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.