Integrating Google map in Android App Tutorial

Tutorials that use the MapActivity. Many using GPS functionality.

Integrating Google map in Android App Tutorial

Postby nancyandroid » Tue Mar 19, 2013 12:23 pm

A friend of mine had written a tutorial on how to embed google maps in an android app here it the tutorial to help you.
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

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


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:
Code: Select all
<?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" >
            <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:
Code: Select all
<?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.
Code: Select all
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);

        //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:
Code: Select all
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();
    }
        . . .
}

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:
Code: Select all
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) {
         . . .
        // 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;
    }
    /* 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) {
    }
    . . .
}


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



Step 9: Add overlay markers
Code: Select all
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() {
        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):
Code: Select all
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;
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);
    }


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.
Code: Select all
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();
            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:
Code: Select all
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {

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


That’s it and you have a fully equipped app providing Google based location services.
User avatar
nancyandroid
Developer
Developer
 
Posts: 27
Joined: Mon Nov 05, 2012 7:51 am

Top

Re: Integrating Google map in Android App Tutorial

Postby nancyandroid » Mon Apr 15, 2013 2:51 pm

Please leave your feedbacks
User avatar
nancyandroid
Developer
Developer
 
Posts: 27
Joined: Mon Nov 05, 2012 7:51 am

Top

Return to Map Tutorials

Who is online

Users browsing this forum: No registered users and 4 guests