Android Google Maps Example Tutorial

Filed Under: Android

In this tutorial we’ll discuss and implement some interesting features of android google maps API in our application. Before we get onto the discussion. Please make sure that you’ve been through the Android Google Maps Setup. It’s a prerequisite.

Android Google Maps API Overview

In this tutorial we’ll implement a few interesting features provided by the Android Google Maps API.

Features include map markers, map types, camera animations and a few more.

Add the map fragment in the content_main.xml layout as we had done in the previous tutorial.

This attaches the MapFragment to our MainActivity.

To get hold of the GoogleMap object in our MainActivity class we need to implement the OnMapReadyCallback interface and override the onMapReady callback method.

Setting Google Map Type

Using the google map object we can change the map type too. There are four different types of map and each give different view of the map. These types are Normal, Hybrid, Satellite and Terrain. We can use them as given below.


googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

Google Map Zoom, Rotation

We can enable/disable map zoom and rotations using the following lines of codes:


googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);

Some other customization methods available in the GoogleMap class are given below.

  1. addCircle(CircleOptions options) : This method add a circle to the map
  2. addPolygon(PolygonOptions options) : This method add a polygon to the map
  3. addTileOverlay(TileOverlayOptions options) : This method add tile overlay to the map
  4. animateCamera(CameraUpdate update) : This method Moves the map according to the update with an animation
  5. clear() : This method removes everything from the map
  6. getMyLocation() : This method returns the currently displayed user location
  7. moveCamera(CameraUpdate update) : This method repositions the camera according to the instructions defined in the update
  8. setTrafficEnabled(boolean enabled) : This method Toggles the traffic layer on or off
  9. snapshot(GoogleMap.SnapshotReadyCallback callback) : This method Takes a snapshot of the map
  10. stopAnimation() : This method stops the camera animation if there is one in progress

Adding Markers on the Google Map


googleMap.addMarker(new MarkerOptions()
            .position(new LatLng(37.4233438,-122.0728817))
            .title("LinkedIn")
            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));

googleMap.addMarker(new MarkerOptions()
        .position(new LatLng(37.4629101,-122.2449094))
        .title("Facebook")
        .snippet("Facebook HQ: Menlo Park"));

googleMap.addMarker(new MarkerOptions()
        .position(new LatLng(37.3092293,-122.1136845))
        .title("Apple"));

snippet() is used to display more data over the marker when it’s tapped.

Animating or moving the camera to a specific point is performed using the following snippet:


googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(37.4233438,-122.0728817),16));

In the above code 16 is the zoom level number. The map zooms in and centers onto the defined LatLng object.

Note: The LatLng object is instantiated and passed with the latitude and longitude double values.

Android Google Maps Example Project Structure

android google maps example tutorial

Android Google Maps Example Code

The MainActivity.java is defined as below:


package com.journaldev.MapsInAction;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

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 MainActivity extends AppCompatActivity implements OnMapReadyCallback {

    SupportMapFragment mapFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mapFragment.getMapAsync(new OnMapReadyCallback() {
                    @Override
                    public void onMapReady(GoogleMap googleMap) {
                        googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

                        googleMap.addMarker(new MarkerOptions()
                                .position(new LatLng(37.4233438, -122.0728817))
                                .title("LinkedIn")
                                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));

                        googleMap.addMarker(new MarkerOptions()
                                .position(new LatLng(37.4629101,-122.2449094))
                                .title("Facebook")
                                .snippet("Facebook HQ: Menlo Park"));

                        googleMap.addMarker(new MarkerOptions()
                                .position(new LatLng(37.3092293, -122.1136845))
                                .title("Apple"));

                        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(37.4233438, -122.0728817), 10));
                    }
                });
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

      googleMap.addMarker(new MarkerOptions()
              .position(new LatLng(37.4233438, -122.0728817))
              .title("LinkedIn")
              .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));

        googleMap.addMarker(new MarkerOptions()
                .position(new LatLng(37.4629101,-122.2449094))
                .title("Facebook")
                .snippet("Facebook HQ: Menlo Park"));

        googleMap.addMarker(new MarkerOptions()
                .position(new LatLng(37.3092293, -122.1136845))
                .title("Apple"));

        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(37.4233438, -122.0728817), 10));
    }
}

We call getMapAsync() on the SupportMapFragment object to register the callback. The FloatingActionButton invokes a new OnMapReadyCallBack method with a different map type.

The content_main.xml contains the MapFragment as shown below:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.journaldev.MapsInAction.MainActivity"
    tools:showIn="@layout/activity_main">

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_gravity="center"
        android:layout_height="match_parent"
        />

</RelativeLayout>

The output of the android google maps example in action is shown below.
android google maps example app

This brings an end to this tutorial. You can download the final Android Google Maps Example project from the below link and replace the YOUR_API_KEY with the your own google maps api key.

Comments

  1. Mangesh Goyal says:

    Hii Anupam,

    I want ask u, Can i use google map in same file means without using new project file?

  2. Irene Hynes says:

    HI Anupam,

    Smokin hot stuff! You’ve trimmed my dim. I feel as bright and fresh as your prolific website and blogs!

    I made the program below in java and compiled with javac command in Window7 (64bit machine). It simply post my machine IP and Mac address to my server application.

    When i run this script with java as >java Macregister
    I get what is expected, the program runs well on my machine.

    When I try to run it on other machines (Win8 – 32 Bit) I get error message and nothing works.
    My problem is 1) to make it compatible for all machines 2) to convert it into JAR application so that it is self executable on different machines.

    I am a new to Java and am struct, please help me out.

    It was cool to see your article pop up in my google search for the process yesterday. Great Guide.
    Keep up the good work!

    Best Regards,
    Irene Hynes

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages