Android google maps example using MapActivity

How to embed google maps in your Android application? Google Maps comes bundled with the Android platform. The following code will show you how to use Google Maps in your Android applications. The sample program does the following...
  • Creates a Map View
  • Use the Geocoder to reverse geocode a given address
  • Get latitude and longitude of locations in Google Maps
  • Add markers to Google Maps
  • Set Zooom


Android google maps using MapActivity

Source for GoogleMapsActivity.java

package com.as400samplecode;

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

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;

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.MotionEvent;
import android.widget.Toast;

public class GoogleMapsActivity extends MapActivity {
    private MapController mapController;
    private MapView mapView;
    private GeoPoint p;

    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.main); // bind the layout to the activity

        // create a map view
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
               
        mapController = mapView.getController();
        Geocoder geoCoder = new Geocoder(this, Locale.getDefault());   
            try {
                List<Address> addresses = 
                    geoCoder.getFromLocationName("2111 North Blackstone Avenue, Fresno, CA 93703-2109", 5);
                if (addresses.size() > 0) {
                    p = new GeoPoint(
                            (int) (addresses.get(0).getLatitude() * 1E6), 
                            (int) (addresses.get(0).getLongitude() * 1E6));
                }   
            } catch (IOException e) {
                e.printStackTrace();
            }

        mapController.setZoom(14);
        mapController.animateTo(p);
       
        //---Add a location marker---
        MapOverlay mapOverlay = new MapOverlay();
        List<Overlay> listOfOverlays = mapView.getOverlays();
        listOfOverlays.clear();
        listOfOverlays.add(mapOverlay);       

        mapView.invalidate();
    }   

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
   
     class MapOverlay extends com.google.android.maps.Overlay
        {
            @Override
            public boolean draw(Canvas canvas, MapView mapView, 
            boolean shadow, long when) 
            {
                super.draw(canvas, mapView, shadow);                  
                 
                //---translate the GeoPoint to screen pixels---
                Point screenPts = new Point();
                mapView.getProjection().toPixels(p, screenPts);
     
                //---add the marker---
                Bitmap bmp = BitmapFactory.decodeResource(
                    getResources(), R.drawable.pushpin);           
                canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);        
                return true;
            }
     
            @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<Address> 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;
            }       
        }


}

Source for main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 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"
        android:textSize="25sp" android:textStyle="bold"
        android:paddingBottom="10dp" />
    <LinearLayout android:layout_height="wrap_content"
        android:id="@+id/linearLayout1" android:layout_width="match_parent"
        android:orientation="vertical">
        <RelativeLayout android:id="@+id/mainlayout"
            android:layout_height="wrap_content" android:layout_width="match_parent">
            <com.google.android.maps.MapView
                android:id="@+id/mapview" android:layout_width="fill_parent"
                android:layout_height="fill_parent" android:clickable="true"
                android:apiKey="???????????????????????????????????????" />
        </RelativeLayout>
    </LinearLayout>

</LinearLayout>

Source for AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.as400samplecode" android:versionCode="1"
    android:versionName="1.0">
    <uses-sdk android:minSdkVersion="13" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <application android:icon="@drawable/icon" android:label="@string/app_name"
        android:theme="@android:style/Theme.Holo.Light">

        <uses-library android:required="true" android:name="com.google.android.maps" />
       
        <activity android:name=".GoogleMapsActivity" 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>

Please Note: You need maps API key for the above example to run. Registering for a Maps API Key is simple, free, and has two parts:

  1. Registering the MD5 fingerprint of the certificate that you will use to sign your application. The Maps registration service then provides you a Maps API Key that is associated with your application's signer certificate.
  2. Adding a reference to the Maps API Key in each MapView, whether declared in XML or instantiated directly from code. You can use the same Maps API Key for any MapView in any Android application, provided that the application is signed with the certificate whose fingerprint you registered with the service.

Click here for Obtaining a Maps API Key



No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.