Home > Uncategorized > Step by Step – Google Map in Android

Step by Step – Google Map in Android

Introduction –
Google Maps is one of the many applications bundled with the Android platform. In addition to simply using the Maps application, you can also embed it into your own applications and make it do some very cool things.

Objective –
Change the views of Google Maps
Obtain the latitude and longitude of locations in Google Maps
Perform geocoding and reverse geocoding
Add markers to Google Maps

Common Issue
API key is incorrect (http://code.google.com/android/add-ons/google-apis/mapkey.html)
You are using the standard Android emulator and not the Google APIs.
You have extended Activity instead of MapActivity


Using Eclipse, create a new Android project and name GoogleMaps as shown in Figure 1

Create project using Eclipse

Obtaining a Maps API key

Beginning with the Android SDK release v1.0, you need to apply for a free Google Maps API key before you can integrate Google Maps into your Android application.
To apply for a key, you need to follow the series of steps outlined below. You can also refer to Google’s detailed documentation on the process at
Google Site for Google Map Key

First, if you are testing the application on the Android emulator, locate the SDK debug certificate located in the default folder of “C:\Documents and Settings\\Local Settings\Application Data\Android”. The filename of the debug keystore is debug.keystore. For deploying to a real Android device, substitute the debug.keystore file with your own keystore file. In a future article I will discuss how you can generate your own keystore file.

For simplicity, copy this file (debug.keystore) to a folder in C:\ (for example, create a folder called “C:\Android”).
Using the debug keystore, you need to extract its MD5 fingerprint using the Keytool.exe application included with your JDK installation. This fingerprint is needed to apply for the free Google Maps key. You can usually find the Keytool.exe from the “C:\Program Files\Java\\bin” folder.

Issue the following command (see also Figure 2) to extract the MD5 fingerprint.

keytool.exe -list -alias androiddebugkey -keystore "C:\android\debug.keystore" -storepass android -keypass android

Copy the MD5 certificate fingerprint and navigate your web browser to: http://code.google.com/android/maps-api-signup.html. Follow the instructions on the page to complete the application and obtain the Google Maps key.
To use the Google Maps in your Android application, you need to modify your AndroidManifest.xml file by adding the element together with the INTERNET permission:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sst.google.map"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MapsActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

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

Displaying Google Map

To display the Google Maps in your Android application, modify the main.xml file located in the res/layout folder. You shall use the element to display the Google Maps in your activity. In addition, let’s use the element to position the map within the activity:
Notice from below that I have used the Google Maps key that I obtained earlier and put it into the apiKey attribute.
In the MapsActivity.java file, modify the class to extend from the MapActivity class, instead of the normal Activity class:

main.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221; android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>  
<com.google.android.maps.MapView
android:id=”@+id/mapView”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:enabled=”true”
android:clickable=”true”
android:apiKey=“0lZa4odnBZCY5DU4Vkd7EFYW-T3Dahuaxvy5QAA” />  
</RelativeLayout >

MapActivity.java

package com.sst.google.map;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import android.os.Bundle;  
public class MapsActivity extends MapActivity
{ /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState); setContentView(R.layout.main);
}  
@Override protected boolean isRouteDisplayed()
{
return false;
}
}

Note – Till point is enough to launch Google Map into Device.

Observe that if your class extends the MapActivity class, you need to override the isRouteDisplayed() method. You can simply do so by setting the method to return false.
That’s it! That’s all you need to do to display the Google Maps in your application. Press F11 in Eclipse to deploy the application onto an Android emulator. Figure 3 shows the Google map in all its glory

Discription

At this juncture, take note of a few troubleshooting details. If your program does not run (i.e. it crashes), then it is likely you forgot to put the following statement in your AndroidManifest.xml file

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

If your application manages to load but you cannot see the map (all you see is a grid), then it is very likely you do not have a valid Map key, or that you did not specify the INTERNET permission:

<uses-permission android:name=”android.permission.INTERNET” />
<uses-permission android:name=”android.permission.ACCESS_GPS” />
<uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” />

Displaying Zoom view

The previous section showed how you can display the Google Maps in your Android device. You can drag the map to any desired location and it will be updated on the fly. However, observe that there is no way to zoom in or out from a particular location. Thus, in this section, you will learn how you can let users zoom into or out of the map.
First, add a element to the main.xml file as shown below:


<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<com.google.android.maps.MapView
android:id="@+id/mapView"
android:clickable="true"
android:enabled="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="0lZa4odnBZCY5DU4Vkd7EFYW-T3Dahuaxvy5QAA"
/>
<LinearLayout android:id="@+id/zoom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
/>
</RelativeLayout >

MapsActivity.java

package com.sst.google.map;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class MapsActivity extends MapActivity {
/** Called when the activity is first created. */
MapView mapView;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mapView = (MapView) findViewById(R.id.mapView);
zoomLayout = (LinearLayout) findViewById(R.id.zoom);
View zoomView = mapView.getZoomControls();
// mapView.setSatellite(true);
zoomLayout.addView(zoomView, new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mapView.displayZoomControls(true);
mc = mapView.getController();
}

@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}

Basically, you obtain the MapView instance on the activity, obtain its zoom controls and then add it to the LinearLayout element you added to the activity earlier on. In the above case, the zoom control will be displayed at the bottom of the screen. When you now press F11 in Eclipse, you will see the zoom controls when you touch the map (see below image).

Google Map - Zoom

Google Map - Zoom

Zoom Control

Using the zoom control, you can zoom in or out of a location by simply touching the “+ or “-” buttons on the screen.
Alternatively, you can also programmatically zoom in or out of the map using the zoomIn() and zoomOut() methods from the MapController class:

public boolean onKeyDown(int keyCode, KeyEvent event)
{
MapController mc = mapView.getController(); switch (keyCode)
{
case KeyEvent.KEYCODE_3: mc.zoomIn(); break;
case KeyEvent.KEYCODE_1: mc.zoomOut();
break;
}
return super.onKeyDown(keyCode, event);
}

In the above code, when the user presses the number 3 on the keyboard the map will zoom in into the next level. Pressing number 1 will zoom out one level.

Changing View of the Maps

By default, the Google Maps displays in the map mode. If you wish to display the map in satellite view, you can use the setSatellite() method of the MapView class, like this:

mapView.setSatellite(true);

You can also display the map in street view, using the setStreetView() method

mapView.setStreetView(true);

Displaying a particular Location

Be default, the Google Maps displays the map of the United States when it is first loaded. However, you can also set the Google Maps to display a particular location. In this case, you can use the animateTo() method of the MapController class.

The following code added in onCreate method
MapView mapView;
MapController mc;
GeoPoint p;

mc = mapView.getController();
String coordinates[] = {"1.352566007", "103.78921587"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);  
p = new GeoPoint( (int) (lat * 1E6), (int) (lng * 1E6));  
mc.animateTo(p);
mc.setZoom(17);
mapView.invalidate();

In the above code, you first obtain a controller from the MapView instance and assign it to a MapController object (mc).
You use a GeoPoint object to represent a geographical location. Note that for this class the latitude and longitude of a location are represented in micro degrees.
This means that they are stored as integer values.
For a latitude value of 40.747778, you need to multiply it by 1e6 to obtain 40747778.
To navigate the map to a particular location, you can use the animateTo() method of the MapController class (an instance which is obtained from the MapView object).
The setZoom() method allows you to specify the zoom level in which the map is displayed.
Figure 6 shows the Google Maps displaying the map of Singapore.

Getting the Location that was touched

After using Google Maps for a while, you may wish to know the latitude and longitude of a location corresponding to the position on the screen that you have just touched.
Knowing this information is very useful as you can find out the address of a location, a process known as Geocoding (you will see how this is done in the next section).
If you have added an overlay to the map, you can override the onTouchEvent() method within the Overlay class.
This method is fired every time the user touches the map. This method has two parameters – MotionEvent and MapView.
Using the MotionEvent parameter, you can know if the user has lifted his finger from the screen using the getAction() method.
In the following code, if the user has touched and then lifted his finger, you will display the latitude and longitude of the location touched:

Following code in MapOverlay class

@Override public boolean onTouchEvent(MotionEvent event, MapView mapView)
{ //---when user lifts his finger---
if (event.getAction() == 1)
{
GeoPoint p = mapView.getProjection().fromPixels( (int) event.getX(), (int) event.getY());
Toast.makeText(getBaseContext(), p.getLatitudeE6() / 1E6 + "," + p.getLongitudeE6() /1E6 , Toast.LENGTH_SHORT).show(); }
return false;
}
}

GeoCoding and Reverse Geocoding

If you know the latitude and longitude of a location, you can find out its address using a process known as Geocoding. Google Maps in Android supports this via the Geocoder class. The following code shows how you can find out the address of a location you have just touched using the getFromLocation() method:

@Override public boolean onTouchEvent(MotionEvent event, MapView mapView)
{ //---when user lifts his finger---
if (event.getAction() == 1)
{ GeoPoint p = mapView.getProjection().fromPixels( (int) event.getX(), (int) event.getY());  
Geocoder geoCoder = new Geocoder( getBaseContext(), Locale.getDefault());
try
{
List

addresses = geoCoder.getFromLocation( p.getLatitudeE6() / 1E6, p.getLongitudeE6() / 1E6, 1);  
String add = ""; if (addresses.size() > 0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); i++) add += addresses.get(0).getAddressLine(i) + "\n";
}  
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e)
{
e.printStackTrace();
}
return true;
}
else return false;
}

Thanks

Advertisements
Categories: Uncategorized
  1. February 19, 2012 at 5:25 pm

    Great article! I loved the insight and advice given. Additionally, your writing style is very pleasing to read. If you have enough time please check out my brand new webpage and let me know what you think.

  2. February 29, 2012 at 9:45 pm

    Rattling nice style and design and superb content, absolutely nothing else we want :D.

  3. March 12, 2012 at 1:12 am

    afternoon everyone im looking for steve johnston is he still about
    alf

  4. March 17, 2012 at 2:39 pm

    Hello Webmaster, I noticed that https://alltechsolution.wordpress.com/2012/02/17/step-by-step-google-map-in-android/ is ranking pretty low on Google and has a low Google PageRank. Now the Google PageRank is how Google is able to see how relevant your webpage is compared to all the other webpages online, if you cannot rank high at the top of Google, then you will NOT get the traffic you need. Now usually trying to get to the top of Google costs hundreds if not thousands of dollars and very highly optimized targeted marketing campaigns that takes a team of experts months to achieve. However, we can show you how to get to the top of Google with no out of pocket expenses (free traffic), no stupid ninja tricks, no silly mind control techniques, and this will be all white hat with no blackhat software or tactics that could possibly land you on bad terms with Google and put you in the dreaded “Google Sandbox”. We’ll show you how to easily capture all the targeted traffic you need, for free, multiple ways to land fast (not months) first-page rankings in Google and other major search engines (Bing, Yahoo, Ask, etc), even show you strategies on how to earn daily commissions just try Ranking Top of Google, please check out our 5 minute video.

  5. March 18, 2012 at 12:27 am

    Great article! I loved the knowledge and also the advice given . Also, your article writing style is very pleasing to read. If you have time please make sure you visit my new webpage and let me know what you think.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: