You are on page 1of 16

Integrating Google map in Android App Tutorial This tutorial is intended for those who are looking to add

Google based location services to their app, to make it more compelling. Requirement: Android 4.0, Eclipse 3.7.2 IDE Step 1: Create a new Android project in Eclipse

info@techaheadcorp.com

TechAhead Software

www.techaheadcorp.com

Step 2: Choose Google API as target SDK

Step 3: Obtain Google Map key To embed Google Map API in your app, you need a valid key. This key can be obtained using keytool command referencing debug.keystore to obtain a fingerprint. keytool list keystore debug.keystore storepass android keypass android

info@techaheadcorp.com

TechAhead Software

www.techaheadcorp.com

After obtaining certificate fingerprint go to https://developers.google.com/android/maps-api-signup, fill in the details and generate your key. Step 4: Modify manifest file You need to modify your AndroidManifest.xml file to be able to use Google Map services, as Google Map libraries are not part of Android library. Add <user-library> element and also give permission to connect to internet in the xml file as shown below: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.techahead.android.googlemaps" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <!-- Add Google Map Library --> <uses-library android:name="com.google.android.maps" /> <activity android:label="@string/app_name" android:name=".AndroidGoogleMapsActivity" >

info@techaheadcorp.com

TechAhead Software

www.techaheadcorp.com

<intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <!-- Allow to connect with internet --> <uses-permission android:name="android.permission.INTERNET" /> </manifest>

Step 5: Now open the main.xml file from /res/layout folder and insert the following code: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <com.google.android.maps.MapView android:id="@+id/mapview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:apiKey="Your Google Maps API key" android:clickable="true" /> </LinearLayout> Step 6: Now open your MainActivity class file and extend it with MapActivity class and make the zoom controllers available through setBuiltInZoomControls(true) method. package com.techahead.android.googlemaps; import android.os.Bundle; import com.google.android.maps.MapActivity; import com.google.android.maps.MapView; public class GoogleMapsActivity extends MapActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //fetch the map view from the layout MapView mapView = (MapView) findViewById(R.id.mapview);

info@techaheadcorp.com

TechAhead Software

www.techaheadcorp.com

//make available zoom controls mapView.setBuiltInZoomControls(true); } @Override protected boolean isRouteDisplayed() { return false; } } Your basic Google Map Application is ready to run on your application. Running the project on the emulator will look like this:

Step 7: Now if you want to display a particular location use the following code:

info@techaheadcorp.com

TechAhead Software

www.techaheadcorp.com

package com.techahead.android.googlemaps; import android.os.Bundle; import com.google.android.maps.MapActivity; import com.google.android.maps.MapView; import com.google.android.maps.MapController; import com.google.android.maps.GeoPoint;

public class GoogleMapsActivity extends MapActivity { @Override public void onCreate(Bundle savedInstanceState) { ... mapView.setBuiltInZoomControls(true); //latitude and longitude of Rome double lat = 41.889882; double lon = 12.479267; //create geo point GeoPoint point = new GeoPoint((int)(lat * 1E6), (int)(lon *1E6)); //get the MapController object MapController controller = mapView.getController(); //animate to the desired point controller.animateTo(point); //set the map zoom to 13 // zoom 1 is top world view controller.setZoom(13); //invalidate the map in order to show changes mapView.invalidate();

info@techaheadcorp.com

TechAhead Software

www.techaheadcorp.com

} ... } In the above code, an object of GeoPoint class is initialized with the longitude and latitude of the desired location to be displayed. An object of MapController class is used with animateTo method to zoom in at a particular point. Step 8: Determining the current location Change your main activity file with the following code: package com.techahead.android.googlemaps; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.widget.Toast; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView;

public class GoogleMapsActivity extends MapActivity implements LocationListener { private MapView mapView; private LocationManager locManager; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { ...

info@techaheadcorp.com

TechAhead Software

www.techaheadcorp.com

// invalidate the map in order to show changes mapView.invalidate(); // Use the location manager through GPS locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, this); //get the current location (last known location) from the location manager Location location = locManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); //if location found display as a toast the current latitude and longitude if (location != null) { Toast.makeText( this, "Current location:\nLatitude: " + location.getLatitude() + "\n" + "Longitude: " + location.getLongitude(), Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "Cannot fetch current location!", Toast.LENGTH_LONG).show(); } //when the current location is found stop listening for updates (preserves battery) locManager.removeUpdates(this); } @Override protected boolean isRouteDisplayed() { return false;

info@techaheadcorp.com

TechAhead Software

www.techaheadcorp.com

} /* When the activity starts up, request updates */ @Override protected void onResume() { super.onResume(); locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0, 0, this); } @Override protected void onPause() { super.onPause(); locManager.removeUpdates(this); //activity pauses => stop listening for updates } @Override public void onLocationChanged(Location location) { } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } ... }

info@techaheadcorp.com

TechAhead Software

www.techaheadcorp.com

In order to run your app without security issues, add following code to your AndroidManifest.xml file: <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Step 9: Add overlay markers To add a marker to the map, you first need to define a class that extends the Overlay class package com.techahead.android.googlemaps; import java.util.ArrayList; import android.content.Context; import android.graphics.drawable.Drawable; import android.view.GestureDetector; import android.view.MotionEvent; import com.google.android.maps.ItemizedOverlay; import com.google.android.maps.MapView; import com.google.android.maps.OverlayItem;

public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> { private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>(); public MyItemizedOverlay(Drawable defaultMarker, Context ctx) { super(boundCenterBottom(defaultMarker)); } public void addOverlay(OverlayItem overlay) { mOverlays.add(overlay); populate(); } public void clear() {

info@techaheadcorp.com

TechAhead Software

www.techaheadcorp.com

mOverlays.clear(); populate(); } @Override protected OverlayItem createItem(int i) { return mOverlays.get(i); } @Override public int size() { return mOverlays.size(); } @Override protected boolean onTap(int index) { return true; } @Override public boolean onTouchEvent(MotionEvent event, MapView mapView){ return false; } }

Next download a pin-like icon and name it marker_pin and place it into /res/drawable folder. Now add the following code to your MainActivity class (here GoogleMapsActivty class):
import android.location.LocationManager; import android.os.Bundle; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.GestureDetector.SimpleOnGestureListener; import android.widget.Toast; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; info@techaheadcorp.com TechAhead Software www.techaheadcorp.com

import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.OverlayItem; public class GoogleMapsActivity extends MapActivity implements LocationListener { private MapView mapView; private MyItemizedOverlay itemizedOverlay; private LocationManager locManager; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { ... //if location found display as a toast the current latitude and longitude if (location != null) { ... point = new GeoPoint((int)(location.getLatitude()*1E6),(int)(location.getLongitude() *1E6)); controller.animateTo(point); } else { ... } // fetch the drawable - the pin that will be displayed on the map Drawable drawable = this.getResources().getDrawable(R.drawable.marker_pin); // create and add an OverlayItem to the MyItemizedOverlay list OverlayItem overlayItem = new OverlayItem(point, "", ""); itemizedOverlay = new MyItemizedOverlay(drawable,this); itemizedOverlay.addOverlay(overlayItem); // add the overlays to the map mapView.getOverlays().add(itemizedOverlay); mapView.invalidate(); //when the current location is found stop listening for updates (preserves battery) locManager.removeUpdates(this); }

info@techaheadcorp.com

TechAhead Software

www.techaheadcorp.com

Your emulator will now look like this:

Step 10: Get touched location (geocoding) and reverse geocoding If you want to know the coordinates (longitude & latitude) of the location you touched (process known as geocoding) you have to create another class that listens for touch events that extends SimpleOnGestureListener class. class MyGestureDetector extends SimpleOnGestureListener {

@Override public boolean onSingleTapConfirmed(MotionEvent event) { // fetch the correspondent point from the map GeoPoint p = mapView.getProjection().fromPixels((int) event.getX(),(int) event.getY()); // create an overlay item and clear all others OverlayItem o = new OverlayItem(p, null, null); itemizedOverlay.clear(); info@techaheadcorp.com TechAhead Software www.techaheadcorp.com

itemizedOverlay.addOverlay(o); // add the overlay item mapView.getOverlays().clear(); mapView.getOverlays().add(itemizedOverlay); mapView.invalidate(); Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault()); // get the address based on the coordinates try { List<Address> addresses = geoCoder.getFromLocation(p.getLatitudeE6() / 1E6, p.getLongitudeE6() / 1E6, 1); addressString = ""; if (addresses.size() > 0) { for (int i = 0; i < addresses.get(0) .getMaxAddressLineIndex(); i++) addressString += addresses.get(0).getAddressLine(i) + " - "; } Toast.makeText(getBaseContext(), addressString, Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return super.onFling(e1, e2, velocityX, velocityY); } @Override public boolean onDown(MotionEvent e) { return false; } } In order to listen to events on touch events change the onTouchEvent() method of the MyItemizedOverlay class like this: public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> { info@techaheadcorp.com TechAhead Software www.techaheadcorp.com

private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>(); private GestureDetector gestureDetector; ... @Override public boolean onTouchEvent(MotionEvent event, MapView mapView) { // when the user lifts its finger if (gestureDetector.onTouchEvent(event)) { return true; } return false; } public GestureDetector getGestureDetector() { return gestureDetector; } public void setGestureDetector(GestureDetector gestureDetector) { this.gestureDetector = gestureDetector; }

Now attach a GestureDetector to your MyItemizedOverlay added objects. In order to do this, add the following code in your MainActivity class after initializing MyItemizedOverlay object:
itemizedOverlay = new MyItemizedOverlay(drawable,this); itemizedOverlay.setGestureDetector(new GestureDetector(new MyGestureDetector()));

Thats it and you have a fully equipped app providing Google based location services.

info@techaheadcorp.com

TechAhead Software

www.techaheadcorp.com

About TechAhead

TechAhead is a leading mobile application development company that has developed hundreds of successful apps. Since its inception in 2009, TechAhead has consistently grown on offerings, clientele, people, reach, and overall value. With our constant urge to be at the top of the ladder, we have mastered ourselves in app development across different platforms, which include iOS, Android, Windows, Blackberry, Amazon, and cross-platform apps. TechAhead has an extensive experience and exposure in Mobile App Development domain. Over time we have devised a view to design, develop, and deliver the most crisp and compelling applications for different smartphones. We call it 3C view connectivity, communication, and cost. We believe that these three elements are the hallmark of any successful enterprise and they should be the starting point for any application development that strives to achieve success likewise. Got a Mobile Application Development requirement? Write to us at info@techaheadcorp.com for a FREE 30-minute no obligation consultation with our blackberry app experts ($200 Value).

You can also reach us on: Website- http://www.techaheadcorp.com/ Fcebook- http://www.facebook.com/TechAhead Twitter - www.twitter.com/TechAhead LinkedIn- www.linkedin.com/company/techahead

info@techaheadcorp.com

TechAhead Software

www.techaheadcorp.com

You might also like