Tuesday, July 31, 2012

Google Map Tutorial Android (Advance)


Hello Android Guys...hope you doing great!!

We know already how to get Google map in our Android App see my earlier tutorial post
Google Map Tutorial Android (Basic)

Note: Because we need to Get Google map API key to Get map in our app
 I have wrote step by step simple tutorial see and put in you main.xml file see below


Okay so today we are going to add some more new things to our Google Maps

1. Enter location name and Go to particular location
2. Bookmark location (POI) place of interest on map
3. Get the location name/coordinates where you touched on map
4. Zoom-in and Zoom-out map location

Let's start coding stuff..create an Android app with



 -------------------------------------------
App Name: GoogleMapAdvance
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 /  Google API 10
Default MapActivity Name: ActivityGoogleMap
-------------------------------------------

ActivityGoogleMap

package com.rdc.gmap;

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

import android.content.Intent;
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.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
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.Overlay;

public class ActivityGoogleMap extends MapActivity 
implements OnClickListener {
 private MapView mapView = null;
 private Button btnGo = null;
 private EditText editLocation = null;
 private MapController mController = null;
 private GeoPoint gPoint = null;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  // to add zoom in and zoom out default buttons
  mapView = (MapView) findViewById(R.id.mapView);
  mapView.setBuiltInZoomControls(true);

  btnGo = (Button) findViewById(R.id.buttonGo);
  btnGo.setOnClickListener(this);

  editLocation = (EditText) findViewById(R.id.editText1);

  // load bangalore as default location
  browseLocation();

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

  mapView.invalidate();
 }

 @Override
 public void onClick(View v) {
  if (btnGo == v) {
   String location = editLocation.getText().toString();
   if (location.equalsIgnoreCase("")) {
   Toast.makeText(getBaseContext(),"Please Enter location!!",
      Toast.LENGTH_SHORT).show();
   } else {

    String map_location = "geo:0,0?q=" + location;
    Uri geoUri = Uri.parse(map_location);
    Intent mapCall = new Intent(Intent.ACTION_VIEW, geoUri);
    startActivity(mapCall);

    // clear old location string
    location = null;
   }

  }

 }

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

 // to load particular location on g-map
 public void browseLocation() {
  mController = mapView.getController();
  String coordinates[] = { "12.917233", "77.620811" };
  double lat = Double.parseDouble(coordinates[0]);
  double lng = Double.parseDouble(coordinates[1]);

  gPoint = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));

  mController.animateTo(gPoint);
  mController.setZoom(17);
 }

 // create inner class to add marker at any place on g-map
 class MapOverlay extends com.google.android.maps.Overlay {

  // add bookmark on map
  @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(gPoint, screenPts);

   // ---add the marker---
   Bitmap bmp = BitmapFactory.decodeResource(getResources(),
     R.drawable.red_pushpin2);
   canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 50, null);
   return true;
  }

  // get the location where you touched on map
  @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;
  }

 }

}
main.xml

Note: make sure you must have Google Map API key to put in Map View in main.xml file
(This is the mistake often made by newbie)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:weightSum="1"
 android:layout_height="fill_parent"
 android:layout_width="fill_parent">
 <LinearLayout
  android:gravity="center"
  android:layout_height="wrap_content"
  android:layout_width="match_parent"
  android:id="@+id/linearLayout1"
  android:layout_weight="0.02"
  android:weightSum="1">
  <Button
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_marginLeft="2dp"
   android:layout_weight=".10"
   android:id="@+id/buttonGo"
   android:text=" Go "></Button>
  <EditText
   android:layout_height="wrap_content"
   android:id="@+id/editText1"
   android:lines="1"
   android:singleLine="true"
   android:layout_width="wrap_content"
   android:layout_marginRight="2dp"
   android:layout_weight=".90"></EditText>
 </LinearLayout>
 <LinearLayout
  android:id="@+id/laymap"
  android:layout_width="fill_parent"
  android:orientation="vertical"
  android:layout_height="wrap_content"
  android:layout_weight="0.98">
  <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="0iuCzAK4N1AoTya_fr62sB7NXXPqkWqF-OCNMEg" />
 </LinearLayout>
<!-- you need to replace your Google map API key here see apiKey="" -->
</LinearLayout>


and Manifest file is

<?xml version="1.0" encoding="utf-8"?>
<manifest
 xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.rdc.gmap"
 android:versionCode="1"
 android:versionName="1.0">
 <uses-sdk android:minSdkVersion="10" />

 <uses-permission android:name="android.permission.INTERNET" />
 <application
  android:icon="@drawable/icon"
  android:label="@string/app_name">

  <uses-library android:name="com.google.android.maps" />
  <activity
   android:name=".ActivityGoogleMap"
   android:theme="@android:style/Theme.NoTitleBar"
   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>


Default Output screen will load as Bangalore and Mark it



 if you touch any place on map it shows details like this

 when you enter any location and click Go...it loads new location...




You can download the complete source code zip file here : GoogleMapAdvance

 cheers!!

 I'd love to hear your thoughts!

3 comments:

  1. 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;


    where you mensioned these package?

    ReplyDelete
  2. hey !!! RDC ....nice blog ....i really like your work .....im a newbie to android ..and i am working on a project ..were ill hav to receive real-time gps location from an android device which can be seen on computer gui or web based interface ...and also ....i should be able to see these real time gps locations on google maps interface real time ....and also ...save these locations to a kml file which can be viewed later ...can you develop an app that can do that .....all help would be very much appreciated ...and all credit of programming will go to you .....pls reply to my email .....

    thank you

    ROHIT

    email:

    rohitereddy@gmail.com ,rohitereddy@hotmail.com

    ReplyDelete
  3. RDC it shows some google maps import problem in app
    for this i included the googleplayservice library.Am i going wrong can you tell me how to do.

    ReplyDelete