Developer

Pro tip: Use Google's Static Maps API to illustrate location in your Android apps

This tutorial shows how simple it is to use Google's free static map SAAS in your Android apps if the Google Maps API requires too much overhead for the desired functionality.

staticmapgoogle0514.png
A static map image of downtown New York City
Image: Google

Most developers are familiar with the Google Maps API. In my opinion, its popularity is rooted in the data it serves up. Google Maps tends to be accurate and pretty quick when responding to millions of requests from all around the world.

However, it's not that easy to work with the Google Maps API. At times I dread going through the associated overhead when the only functionality I need is a static map image of a particular location. Recently I stumbled across another Google Maps related API that is specifically for serving up static images based on a latitude / longitude pair. The best part is it's dead simple to use.

Follow along with the tutorial below, or download and import the entire project directly into Eclipse. Ready?

1. Create a new Android project in Eclipse. Target SDK 14 (ICS) or better.

2. In your manifest file, you'll need to add the internet permission.

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.googlestaticmapssaas"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.googlestaticmapssaas.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

3. Our layout consists of a text view and an image view wrapped by a linear layout. Make the needed modifications in your /res/layouts folder.

activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Google HQ" />
    
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/img"
        android:background="#cacaca"/>

</LinearLayout>

4. We need to set our image view source to the remote URL that is the Google Maps endpoint. We do this in the /src/MainActivity.java file. For the purpose of this demonstration, I'm doing all the work in the on create override. Note that, because the image needs to be downloaded, we have to throw that processing off onto a background thread to keep our UI from stuttering on startup.

MainActivity.java
package com.example.googlestaticmapssaas;

import java.io.InputStream;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class MainActivity extends Activity {
	
	protected static final String STATIC_MAP_API_ENDPOINT = "http://maps.google.com/maps/api/staticmap?center=37.4223662,-122.0839445&zoom=15&size=200x200&sensor=false";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		AsyncTask<Void, Void, Bitmap> setImageFromUrl = new AsyncTask<Void, Void, Bitmap>(){
			@Override
			protected Bitmap doInBackground(Void... params) {
				Bitmap bmp = null;
		        HttpClient httpclient = new DefaultHttpClient();   
		        HttpGet request = new HttpGet(STATIC_MAP_API_ENDPOINT); 

		        InputStream in = null;
		        try {
		            in = httpclient.execute(request).getEntity().getContent();
		            bmp = BitmapFactory.decodeStream(in);
		            in.close();
		        } catch (Exception e) {
		            e.printStackTrace();
		        } 
				return bmp;
			}
			protected void onPostExecute(Bitmap bmp) {
				if (bmp!=null) {
					final ImageView iv = (ImageView) findViewById(R.id.img);
					iv.setImageBitmap(bmp);
				}
			}
		};
		setImageFromUrl.execute();
	}
}

That's all there is to it. Though before you copy and paste the code directly into your next app, be sure to read Google's usage and API key requirements. It's pretty generous and in most cases should be just fine, but it's always a good idea to know what you're agreeing to before your app tops the charts.

googlestaticmapssaas070714.png

About William J. Francis

William J Francis began programming computers at age eleven. Specializing in embedded and mobile platforms, he has more than 20 years of professional software engineering under his belt, including a four year stint in the US Army's Military Intellige...

Editor's Picks

Free Newsletters, In your Inbox