Integrating Google Map in Android App Tutorial

download Integrating Google Map in Android App Tutorial

of 16

Transcript of Integrating Google Map in Android App Tutorial

  • 7/29/2019 Integrating Google Map in Android App Tutorial

    1/16

    [email protected] TechAhead Software www.techaheadcorp.com

    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

  • 7/29/2019 Integrating Google Map in Android App Tutorial

    2/16

    [email protected] 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 listkeystore debug.keystore storepass android keypass android

  • 7/29/2019 Integrating Google Map in Android App Tutorial

    3/16

    [email protected] TechAhead Software www.techaheadcorp.com

    After obtaining certificate fingerprint go tohttps://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 GoogleMap libraries are not part of Android library. Add element and also give permission to

    connect to internet in the xml file as shown below:

    https://developers.google.com/android/maps-api-signuphttps://developers.google.com/android/maps-api-signuphttps://developers.google.com/android/maps-api-signuphttp://schemas.android.com/apk/res/androidhttp://schemas.android.com/apk/res/androidhttp://schemas.android.com/apk/res/androidhttp://schemas.android.com/apk/res/androidhttps://developers.google.com/android/maps-api-signup
  • 7/29/2019 Integrating Google Map in Android App Tutorial

    4/16

    [email protected] TechAhead Software www.techaheadcorp.com

    Step 5: Now open the main.xml file from /res/layout folder and insert the following code:

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

  • 7/29/2019 Integrating Google Map in Android App Tutorial

    5/16

    [email protected] 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:

  • 7/29/2019 Integrating Google Map in Android App Tutorial

    6/16

    [email protected] 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();

  • 7/29/2019 Integrating Google Map in Android App Tutorial

    7/16

    [email protected] TechAhead Software www.techaheadcorp.com

    }

    . . .

    }

    In the above code, an object of GeoPoint class is initialized with the longitude and latitude of the desiredlocation 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) {

    . . .

  • 7/29/2019 Integrating Google Map in Android App Tutorial

    8/16

    [email protected] 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;

  • 7/29/2019 Integrating Google Map in Android App Tutorial

    9/16

    [email protected] 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) {

    }

    . . .

    }

  • 7/29/2019 Integrating Google Map in Android App Tutorial

    10/16

    [email protected] TechAhead Software www.techaheadcorp.com

    In order to run your app without security issues, add following code to your AndroidManifest.xml file:

    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 {

    private ArrayList mOverlays = new ArrayList();

    public MyItemizedOverlay(Drawable defaultMarker, Context ctx) {

    super(boundCenterBottom(defaultMarker));

    }

    public void addOverlay(OverlayItem overlay) {

    mOverlays.add(overlay);

    populate();

    }

    public void clear() {

  • 7/29/2019 Integrating Google Map in Android App Tutorial

    11/16

    [email protected] 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;

  • 7/29/2019 Integrating Google Map in Android App Tutorial

    12/16

    [email protected] 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 mapmapView.getOverlays().add(itemizedOverlay);

    mapView.invalidate();

    //when the current location is found stop listening for updates (preserves battery)

    locManager.removeUpdates(this);

    }

  • 7/29/2019 Integrating Google Map in Android App Tutorial

    13/16

    [email protected] 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 {

    @Overridepublic 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();

  • 7/29/2019 Integrating Google Map in Android App Tutorial

    14/16

    [email protected] 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 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

    MyItemizedOverlayclass like this:

    public class MyItemizedOverlay extends ItemizedOverlay {

  • 7/29/2019 Integrating Google Map in Android App Tutorial

    15/16

    [email protected] TechAhead Software www.techaheadcorp.com

    private ArrayList mOverlays = new ArrayList();

    private GestureDetector gestureDetector;

    . . .

    @Overridepublic 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 yourMyItemizedOverlay added objects. In order to do this, add

    the following code in your MainActivity class after initializingMyItemizedOverlay 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.

  • 7/29/2019 Integrating Google Map in Android App Tutorial

    16/16

    [email protected] 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 [email protected] 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

    http://www.techaheadcorp.com/mobile-application-development.phphttp://www.techaheadcorp.com/mobile-application-development.phphttp://www.techaheadcorp.com/mobile-application-development.phpmailto:[email protected]:[email protected]:[email protected]://www.techaheadcorp.com/http://www.techaheadcorp.com/http://www.facebook.com/TechAheadhttp://www.facebook.com/TechAheadhttp://www.twitter.com/TechAheadhttp://www.twitter.com/TechAheadhttp://www.linkedin.com/company/techaheadhttp://www.linkedin.com/company/techaheadhttp://www.linkedin.com/company/techaheadhttp://www.linkedin.com/company/techaheadhttp://www.linkedin.com/company/techaheadhttp://www.linkedin.com/company/techaheadhttp://www.linkedin.com/company/techaheadhttp://www.twitter.com/TechAheadhttp://www.twitter.com/TechAheadhttp://www.twitter.com/TechAheadhttp://www.twitter.com/TechAheadhttp://www.twitter.com/TechAheadhttp://www.facebook.com/TechAheadhttp://www.facebook.com/TechAheadhttp://www.facebook.com/TechAheadhttp://www.facebook.com/TechAheadhttp://www.facebook.com/TechAheadhttp://www.techaheadcorp.com/http://www.techaheadcorp.com/http://www.techaheadcorp.com/http://www.techaheadcorp.com/http://www.techaheadcorp.com/mailto:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]://www.techaheadcorp.com/mobile-application-development.phphttp://www.techaheadcorp.com/mobile-application-development.phphttp://www.techaheadcorp.com/mobile-application-development.phphttp://www.techaheadcorp.com/mobile-application-development.php