Starting with Google Maps V2 in Android – Simple Implementation

By | January 27, 2016

Hi all,

In today’s tutorial lets see

1. How we can add a Google Map to our Android project using Android Studio?
2. Showing a location in the Google Map.
3. Adding Markers in Google Map.
4. Getting location on Tapping on Marker info Window in Google Maps.

CardView in Android

Before you start coding, make sure Android studio is all set up for Running the Maps application.

You will need Google play Services

In the app-level build.gradle add this


buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.5.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

In the Module-level build.gradle add this in the dependencies

dependencies{
	compile 'com.google.android.gms:play-services:8.4.0'
	compile 'com.android.support:support-v4:23.1.1'
}

android{
	compileSdkVersion 'Google Inc.:Google APIs:23'    
	buildToolsVersion '23.0.2'
}

These are the main things you may have your own settings in the build.gradle.

How we can add a Google Map to our Android project using Android Studio?

Take a look at the screenshot for adding new project to your Android Studio and click finish.

Google Maps Android

Now Google will create everything you need for a MapActivity except the Google Maps Key.
You need to get the Google maps key before proceeding.

For that you need to sign in to Google and navigate to https://developers.google.com/maps/documentation/android-api/.

Follow the instructions and get the key.

A sample key would look like this.

“AIzaSyC1mQQLwwcms-bAaNmhKUNiW_HBjftQiSE”

Once you get the key, you can start coding.

Now we will check our layout.
In the layout I am adding once edittext to search for a location in maps.

The final layout would look like this.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/searchTxt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:layout_alignParentTop="true"
        android:hint="Enter ur shop location"/>

    <fragment
        android:id="@+id/map"
        android:layout_below="@+id/searchTxt"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout="@layout/abc_action_bar_title_item" />

</RelativeLayout>

Here is our Activity…

This is the complete activity where we will add a marker on searched location.
Then we will add a tap listener on the info window in the marker to get the location.


package com.coderzheaven.maps_demo;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

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.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.GeoPoint;
import com.modivmedia.mcscan.R;

import java.util.List;

public class MapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMarkerClickListener {

    private GoogleMap mMap;
    public static final String TAG = "MAP";
    EditText searchLocationTv;

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

        searchLocationTv = (EditText) findViewById(R.id.searchTxt);

        // 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);

        // Acquire a reference to the system Location Manager
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        // Define a listener that responds to location updates
        LocationListener locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                // Called when a new location is found by the network location provider.
                setLocationInMap(location);
            }

            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            public void onProviderEnabled(String provider) {
            }

            public void onProviderDisabled(String provider) {
            }
        };

        // Register the listener with the Location Manager to receive location updates
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

        searchLocationTv.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) ||
                        (actionId == EditorInfo.IME_ACTION_DONE)) {
                    Log.i(TAG, "Enter pressed");
                    GeoPoint g = getLocationFromAddress(searchLocationTv.getText().toString().trim());

                    double latitude = g.getLatitudeE6() / 1E6;
                    double longitude = g.getLongitudeE6() / 1E6;

                    Location location = new Location(searchLocationTv.getText().toString().trim());
                    location.setLatitude(latitude);
                    location.setLongitude(longitude);

                    setLocationInMap(location);
                }
                return false;
            }
        });
    }


    /**
     * 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;
        mMap.setOnMarkerClickListener(this);
        Log.i(TAG, "Map is ready...");

        mMap.setOnInfoWindowClickListener(
                new GoogleMap.OnInfoWindowClickListener() {
                    @Override
                    public void onInfoWindowClick(Marker arg0) {

                        // TODO Auto-generated method stub
                        arg0.hideInfoWindow();
                        double dlat = arg0.getPosition().latitude;
                        double dlon = arg0.getPosition().longitude;
                        String slat = String.valueOf(dlat);
                        String slon = String.valueOf(dlon);
                        Log.i(TAG, "LAt " + dlat + "Long = " + dlon);
                    }
                }
        );
    }

    private void setLocationInMap(Location location) {
        Log.i(TAG, "Setting Location in Map...");
        LatLng myLocation = new LatLng(location.getLatitude(), location.getLongitude());
        mMap.addMarker(new MarkerOptions().position(myLocation).title(searchLocationTv.getText().toString().trim())).showInfoWindow();
        CameraPosition cameraPosition = new CameraPosition.Builder().target(myLocation).zoom(2).build();
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    }

    //Find 5 names and return the first one for the name provided..
    private GeoPoint getLocationFromAddress(String strAddress) {

        Geocoder coder = new Geocoder(this);
        List<Address> address;
        GeoPoint p1 = null;

        try {
            address = coder.getFromLocationName(strAddress, 5);
            if (address == null) {
                return null;
            }
            Address location = address.get(0);
            location.getLatitude();
            location.getLongitude();

            p1 = new GeoPoint((int) (location.getLatitude() * 1E6),
                    (int) (location.getLongitude() * 1E6));
        } catch (Exception e) {

        }
        return p1;
    }

    @Override
    public boolean onMarkerClick(final Marker marker) {
        Log.i(TAG, "marker clicked");
        marker.showInfoWindow();
        return true;
    }
}

Here is how the AndroidManifest.xml will look like..

Make sure you add the permissions for location and internet here..
Also add the Android Maps API key.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.coderzheaven.maps_demo"
    android:installLocation="auto">

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

    <!-- Permission for requesting location updates -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <permission
        android:name="com.coderzheaven.maps_demo.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.coderzheaven.maps_demo.permission.MAPS_RECEIVE"/>

    <application
        android:allowBackup="true"
        android:largeHeap="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

        <uses-library android:name="com.google.android.maps" />

        <activity
            android:name="com.coderzheaven.maps_demo.MapActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.NoTitleBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <!--Google MAP API key-->

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyC1mQQLwwcms-bAaNmhKUNiW_HBjftQiSE" />
    </application>

</manifest>

You are now ready to run the application.

Leave a Reply

Your email address will not be published. Required fields are marked *