main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#efab00"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/tablayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:visibility="gone" >
</LinearLayout>
<com.google.android.maps.MapView
android:id="@+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@+id/bottomlayout"
android:layout_below="@+id/tablayout"
android:apiKey="0vhRtRSX4ZNpVfcGL73Z9AO23GGEzrScRkAxFng"
android:clickable="true"
android:enabled="true" />
<LinearLayout
android:id="@+id/bottomlayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/btnlayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:gravity="center"
>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Java Classes:
Main Activity class:
package com.androidhive.googlemaps;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.Chronometer;
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 com.google.android.maps.OverlayItem;
public class AndroidGoogleMapsActivity extends MapActivity implements
OnClickListener {
Chronometer mChronometer;
Drawable drawable;
MyItemizedOverlay itemizedOverlay;
double src_lat, src_long;
MapView mapView;
Button stop, start;
private MapController mc;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
mChronometer = (Chronometer) findViewById(R.id.chronometer);
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
stop = (Button) findViewById(R.id.button2);
start = (Button) findViewById(R.id.button1);
start.setOnClickListener(this);
stop.setOnClickListener(this);
}
@Override
protected boolean isRouteDisplayed() {
return true;
}
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.button2:
String latitude = "13.059517017166014";
String londtitude = "80.19573211669922";
src_lat = Float.parseFloat(latitude);
src_long = Float.parseFloat(londtitude);
mapView.setStreetView(true);
mc = mapView.getController();
List<Overlay> mapOverlays = mapView.getOverlays();
drawable = getResources().getDrawable(R.drawable.mark_red);
itemizedOverlay = new MyItemizedOverlay(drawable, mapView);
GeoPoint point = new GeoPoint((int) (src_lat * 1E6),
(int) (src_long * 1E6));
OverlayItem overlayItem = new OverlayItem(point, latitude,
londtitude);
itemizedOverlay.addOverlay(overlayItem);
mapOverlays.add(itemizedOverlay);
final MapController mc = mapView.getController();
mc.animateTo(point);
mc.setZoom(16);
break;
case R.id.button1:
double dest_lat = 13.072162819603713;
double dest_long = 80.20195484161377;
List<Overlay> mapOverlays1 = mapView.getOverlays();
itemizedOverlay = new MyItemizedOverlay(drawable, mapView);
GeoPoint srcGeoPoint = new GeoPoint((int) (src_lat * 1E6),
(int) (src_long * 1E6));
OverlayItem overlayItem1 = new OverlayItem(srcGeoPoint, "", "");
itemizedOverlay.addOverlay(overlayItem1);
GeoPoint destGeoPoint = new GeoPoint((int) (dest_lat * 1E6),
(int) (dest_long * 1E6));
OverlayItem overlayItem2 = new OverlayItem(destGeoPoint, "", "");
itemizedOverlay.addOverlay(overlayItem2);
mapOverlays1.add(itemizedOverlay);
DrawPath(srcGeoPoint, destGeoPoint, Color.RED, mapView);
mapView.getController().animateTo(srcGeoPoint);
mapView.getController().setZoom(15);
break;
}
}
private void DrawPath(GeoPoint src, GeoPoint dest, int color,
MapView mMapView01) {
// connect to map web service
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");// from
urlString.append(Double.toString((double) src.getLatitudeE6() / 1.0E6));
urlString.append(",");
urlString
.append(Double.toString((double) src.getLongitudeE6() / 1.0E6));
urlString.append("&daddr=");// to
urlString
.append(Double.toString((double) dest.getLatitudeE6() / 1.0E6));
urlString.append(",");
urlString
.append(Double.toString((double) dest.getLongitudeE6() / 1.0E6));
urlString.append("&ie=UTF8&0&om=0&output=kml");
Log.d("xxx", "URL=" + urlString.toString());
// get the kml (XML) doc. And parse it to get the coordinates(direction
// route).
Document doc = null;
HttpURLConnection urlConnection = null;
URL url = null;
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(urlConnection.getInputStream());
if (doc.getElementsByTagName("GeometryCollection").getLength() > 0) {
// String path =
// doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getNodeName();
String path = doc.getElementsByTagName("GeometryCollection")
.item(0).getFirstChild().getFirstChild()
.getFirstChild().getNodeValue();
Log.d("xxx", "path=" + path);
String[] pairs = path.split(" ");
String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude
// lngLat[1]=latitude
// lngLat[2]=height
// src
GeoPoint startGP = new GeoPoint(
(int) (Double.parseDouble(lngLat[1]) * 1E6),
(int) (Double.parseDouble(lngLat[0]) * 1E6));
mMapView01.getOverlays()
.add(new MyOverLay(startGP, startGP, 1));
GeoPoint gp1;
GeoPoint gp2 = startGP;
for (int i = 1; i < pairs.length; i++) // the last one would be
// crash
{
lngLat = pairs[i].split(",");
gp1 = gp2;
// watch out! For GeoPoint, first:latitude, second:longitude
gp2 = new GeoPoint(
(int) (Double.parseDouble(lngLat[1]) * 1E6),
(int) (Double.parseDouble(lngLat[0]) * 1E6));
mMapView01.getOverlays().add(
new MyOverLay(gp1, gp2, 2, color));
Log.d("xxx", "pair:" + pairs[i]);
}
mMapView01.getOverlays().add(new MyOverLay(dest, dest, 3)); // use
// the
// default
// color
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
}
/*
* Read more: http://csie-tw.blogspot.com/2009/06/android-driving-direction-route-path.html
*
*/
package com.androidhive.googlemaps;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
public class MyOverLay extends Overlay
{
private GeoPoint gp1;
private GeoPoint gp2;
private int mRadius=6;
private int mode=0;
private int defaultColor;
private String text="";
private Bitmap img = null;
public MyOverLay(GeoPoint gp1,GeoPoint gp2,int mode) // GeoPoint is a int. (6E)
{
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
defaultColor = 999; // no defaultColor
}
public MyOverLay(GeoPoint gp1,GeoPoint gp2,int mode, int defaultColor)
{
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
this.defaultColor = defaultColor;
}
public void setText(String t)
{
this.text = t;
}
public void setBitmap(Bitmap bitmap)
{
this.img = bitmap;
}
public int getMode()
{
return mode;
}
@Override
public boolean draw
(Canvas canvas, MapView mapView, boolean shadow, long when)
{
Projection projection = mapView.getProjection();
if (shadow == false)
{
Paint paint = new Paint();
paint.setAntiAlias(true);
Point point = new Point();
projection.toPixels(gp1, point);
// mode=1¡Gstart
if(mode==1)
{
if(defaultColor==999)
paint.setColor(Color.BLUE);
else
paint.setColor(defaultColor);
RectF oval=new RectF(point.x - mRadius, point.y - mRadius,
point.x + mRadius, point.y + mRadius);
// start point
// canvas.drawOval(oval, paint);
}
// mode=2¡Gpath
else if(mode==2)
{
if(defaultColor==999)
paint.setColor(Color.RED);
else
paint.setColor(defaultColor);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(5);
paint.setAlpha(120);
canvas.drawLine(point.x, point.y, point2.x,point2.y, paint);
}
/* mode=3¡Gend */
else if(mode==3)
{
/* the last path */
if(defaultColor==999)
paint.setColor(Color.GREEN);
else
paint.setColor(defaultColor);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(5);
paint.setAlpha(120);
canvas.drawLine(point.x, point.y, point2.x,point2.y, paint);
RectF oval=new RectF(point2.x - mRadius,point2.y - mRadius,
point2.x + mRadius,point2.y + mRadius);
/* end point */
paint.setAlpha(255);
// canvas.drawOval(oval, paint);
}
/* mode=4¡Gcar */
else if(mode==4)
{
if(defaultColor==999)
paint.setColor(Color.GREEN);
else
paint.setColor(defaultColor);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setTextSize(20);
paint.setAntiAlias(true);
canvas.drawBitmap(img, point2.x, point2.y,paint);
canvas.drawText(this.text, point2.x, point2.y, paint);
// Log.d(TAG, "Draw the text="+this.text+ " at point="+point2.x + "," + point2.y);
}
else if(mode==5)
{
if(defaultColor==999)
paint.setColor(Color.GREEN);
else
paint.setColor(defaultColor);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setTextSize(20);
paint.setAntiAlias(true);
canvas.drawBitmap(img, point2.x, point2.y,paint);
// Log.d(TAG, "Draw the text="+this.text+ " at point="+point2.x + "," + point2.y);
}
}
return super.draw(canvas, mapView, shadow, when);
}
}
MyItemizedOverlay.java
/***
* Copyright (c) 2010 readyState Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.androidhive.googlemaps;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.widget.Toast;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
public class MyItemizedOverlay extends BalloonItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> m_overlays = new ArrayList<OverlayItem>();
private Context c;
public MyItemizedOverlay(Drawable defaultMarker, MapView mapView) {
super(boundCenter(defaultMarker), mapView);
c = mapView.getContext();
}
public void addOverlay(OverlayItem overlay) {
m_overlays.add(overlay);
populate();
}
@Override
protected OverlayItem createItem(int i) {
return m_overlays.get(i);
}
@Override
public int size() {
return m_overlays.size();
}
@Override
protected boolean onBalloonTap(int index, OverlayItem item) {
/*Toast.makeText(c, "LOCATION " + index,
Toast.LENGTH_LONG).show();*/
return true;
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#efab00"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/tablayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:visibility="gone" >
</LinearLayout>
<com.google.android.maps.MapView
android:id="@+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@+id/bottomlayout"
android:layout_below="@+id/tablayout"
android:apiKey="0vhRtRSX4ZNpVfcGL73Z9AO23GGEzrScRkAxFng"
android:clickable="true"
android:enabled="true" />
<LinearLayout
android:id="@+id/bottomlayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/btnlayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:gravity="center"
>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Java Classes:
Main Activity class:
package com.androidhive.googlemaps;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.Chronometer;
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 com.google.android.maps.OverlayItem;
public class AndroidGoogleMapsActivity extends MapActivity implements
OnClickListener {
Chronometer mChronometer;
Drawable drawable;
MyItemizedOverlay itemizedOverlay;
double src_lat, src_long;
MapView mapView;
Button stop, start;
private MapController mc;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
mChronometer = (Chronometer) findViewById(R.id.chronometer);
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
stop = (Button) findViewById(R.id.button2);
start = (Button) findViewById(R.id.button1);
start.setOnClickListener(this);
stop.setOnClickListener(this);
}
@Override
protected boolean isRouteDisplayed() {
return true;
}
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.button2:
String latitude = "13.059517017166014";
String londtitude = "80.19573211669922";
src_lat = Float.parseFloat(latitude);
src_long = Float.parseFloat(londtitude);
mapView.setStreetView(true);
mc = mapView.getController();
List<Overlay> mapOverlays = mapView.getOverlays();
drawable = getResources().getDrawable(R.drawable.mark_red);
itemizedOverlay = new MyItemizedOverlay(drawable, mapView);
GeoPoint point = new GeoPoint((int) (src_lat * 1E6),
(int) (src_long * 1E6));
OverlayItem overlayItem = new OverlayItem(point, latitude,
londtitude);
itemizedOverlay.addOverlay(overlayItem);
mapOverlays.add(itemizedOverlay);
final MapController mc = mapView.getController();
mc.animateTo(point);
mc.setZoom(16);
break;
case R.id.button1:
double dest_lat = 13.072162819603713;
double dest_long = 80.20195484161377;
List<Overlay> mapOverlays1 = mapView.getOverlays();
itemizedOverlay = new MyItemizedOverlay(drawable, mapView);
GeoPoint srcGeoPoint = new GeoPoint((int) (src_lat * 1E6),
(int) (src_long * 1E6));
OverlayItem overlayItem1 = new OverlayItem(srcGeoPoint, "", "");
itemizedOverlay.addOverlay(overlayItem1);
GeoPoint destGeoPoint = new GeoPoint((int) (dest_lat * 1E6),
(int) (dest_long * 1E6));
OverlayItem overlayItem2 = new OverlayItem(destGeoPoint, "", "");
itemizedOverlay.addOverlay(overlayItem2);
mapOverlays1.add(itemizedOverlay);
DrawPath(srcGeoPoint, destGeoPoint, Color.RED, mapView);
mapView.getController().animateTo(srcGeoPoint);
mapView.getController().setZoom(15);
break;
}
}
private void DrawPath(GeoPoint src, GeoPoint dest, int color,
MapView mMapView01) {
// connect to map web service
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");// from
urlString.append(Double.toString((double) src.getLatitudeE6() / 1.0E6));
urlString.append(",");
urlString
.append(Double.toString((double) src.getLongitudeE6() / 1.0E6));
urlString.append("&daddr=");// to
urlString
.append(Double.toString((double) dest.getLatitudeE6() / 1.0E6));
urlString.append(",");
urlString
.append(Double.toString((double) dest.getLongitudeE6() / 1.0E6));
urlString.append("&ie=UTF8&0&om=0&output=kml");
Log.d("xxx", "URL=" + urlString.toString());
// get the kml (XML) doc. And parse it to get the coordinates(direction
// route).
Document doc = null;
HttpURLConnection urlConnection = null;
URL url = null;
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(urlConnection.getInputStream());
if (doc.getElementsByTagName("GeometryCollection").getLength() > 0) {
// String path =
// doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getNodeName();
String path = doc.getElementsByTagName("GeometryCollection")
.item(0).getFirstChild().getFirstChild()
.getFirstChild().getNodeValue();
Log.d("xxx", "path=" + path);
String[] pairs = path.split(" ");
String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude
// lngLat[1]=latitude
// lngLat[2]=height
// src
GeoPoint startGP = new GeoPoint(
(int) (Double.parseDouble(lngLat[1]) * 1E6),
(int) (Double.parseDouble(lngLat[0]) * 1E6));
mMapView01.getOverlays()
.add(new MyOverLay(startGP, startGP, 1));
GeoPoint gp1;
GeoPoint gp2 = startGP;
for (int i = 1; i < pairs.length; i++) // the last one would be
// crash
{
lngLat = pairs[i].split(",");
gp1 = gp2;
// watch out! For GeoPoint, first:latitude, second:longitude
gp2 = new GeoPoint(
(int) (Double.parseDouble(lngLat[1]) * 1E6),
(int) (Double.parseDouble(lngLat[0]) * 1E6));
mMapView01.getOverlays().add(
new MyOverLay(gp1, gp2, 2, color));
Log.d("xxx", "pair:" + pairs[i]);
}
mMapView01.getOverlays().add(new MyOverLay(dest, dest, 3)); // use
// the
// default
// color
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
}
AddItemizedOverlay.java
package com.androidhive.googlemaps;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
public class AddItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
private Context context;
public AddItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public AddItemizedOverlay(Drawable defaultMarker, Context context) {
this(defaultMarker);
this.context = context;
}
@Override
protected OverlayItem createItem(int i) {
return mapOverlays.get(i);
}
@Override
public int size() {
return mapOverlays.size();
}
@Override
protected boolean onTap(int index) {
Log.e("Tap", "Tap Performed");
return true;
}
public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
this.populate();
}
/**
* Getting Latitude and Longitude on Touch event
* **/
@Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
if (event.getAction() == 1) {
GeoPoint geopoint = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
// latitude
double lat = geopoint.getLatitudeE6() / 1E6;
// longitude
double lon = geopoint.getLongitudeE6() / 1E6;
Toast.makeText(context, "Lat: " + lat + ", Lon: "+lon, Toast.LENGTH_SHORT).show();
}
return false;
}
}
BalloonItemizedOverlay.java
/***
* Copyright (c) 2010 readyState Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.androidhive.googlemaps;
import java.util.List;
import android.graphics.drawable.Drawable;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
/**
* An abstract extension of ItemizedOverlay for displaying an information balloon
* upon screen-tap of each marker overlay.
*
* @author Jeff Gilfelt
*/
public abstract class BalloonItemizedOverlay<Item extends OverlayItem> extends ItemizedOverlay<Item> {
private MapView mapView;
private BalloonOverlayView<Item> balloonView;
private View clickRegion;
private int viewOffset;
final MapController mc;
private Item currentFocussedItem;
private int currentFocussedIndex;
/**
* Create a new BalloonItemizedOverlay
*
* @param defaultMarker - A bounded Drawable to be drawn on the map for each item in the overlay.
* @param mapView - The view upon which the overlay items are to be drawn.
*/
public BalloonItemizedOverlay(Drawable defaultMarker, MapView mapView) {
super(defaultMarker);
this.mapView = mapView;
viewOffset = 0;
mc = mapView.getController();
}
/**
* Set the horizontal distance between the marker and the bottom of the information
* balloon. The default is 0 which works well for center bounded markers. If your
* marker is center-bottom bounded, call this before adding overlay items to ensure
* the balloon hovers exactly above the marker.
*
* @param pixels - The padding between the center point and the bottom of the
* information balloon.
*/
public void setBalloonBottomOffset(int pixels) {
viewOffset = pixels;
}
public int getBalloonBottomOffset() {
return viewOffset;
}
/**
* Override this method to handle a "tap" on a balloon. By default, does nothing
* and returns false.
*
* @param index - The index of the item whose balloon is tapped.
* @param item - The item whose balloon is tapped.
* @return true if you handled the tap, otherwise false.
*/
protected boolean onBalloonTap(int index, Item item) {
return false;
}
/* (non-Javadoc)
* @see com.google.android.maps.ItemizedOverlay#onTap(int)
*/
@Override
protected final boolean onTap(int index) {
currentFocussedIndex = index;
currentFocussedItem = createItem(index);
boolean isRecycled;
if (balloonView == null) {
balloonView = createBalloonOverlayView();
clickRegion = (View) balloonView.findViewById(R.id.balloon_inner_layout);
clickRegion.setOnTouchListener(createBalloonTouchListener());
isRecycled = false;
} else {
isRecycled = true;
}
balloonView.setVisibility(View.GONE);
List<Overlay> mapOverlays = mapView.getOverlays();
if (mapOverlays.size() > 1) {
hideOtherBalloons(mapOverlays);
}
balloonView.setData(currentFocussedItem);
GeoPoint point = currentFocussedItem.getPoint();
MapView.LayoutParams params = new MapView.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, point,
MapView.LayoutParams.BOTTOM_CENTER);
params.mode = MapView.LayoutParams.MODE_MAP;
balloonView.setVisibility(View.VISIBLE);
if (isRecycled) {
balloonView.setLayoutParams(params);
} else {
mapView.addView(balloonView, params);
}
mc.animateTo(point);
return true;
}
/**
* Creates the balloon view. Override to create a sub-classed view that
* can populate additional sub-views.
*/
protected BalloonOverlayView<Item> createBalloonOverlayView() {
return new BalloonOverlayView<Item>(getMapView().getContext(), getBalloonBottomOffset());
}
/**
* Expose map view to subclasses.
* Helps with creation of balloon views.
*/
protected MapView getMapView() {
return mapView;
}
/**
* Sets the visibility of this overlay's balloon view to GONE.
*/
protected void hideBalloon() {
if (balloonView != null) {
balloonView.setVisibility(View.GONE);
}
}
/**
* Hides the balloon view for any other BalloonItemizedOverlay instances
* that might be present on the MapView.
*
* @param overlays - list of overlays (including this) on the MapView.
*/
private void hideOtherBalloons(List<Overlay> overlays) {
for (Overlay overlay : overlays) {
if (overlay instanceof BalloonItemizedOverlay<?> && overlay != this) {
((BalloonItemizedOverlay<?>) overlay).hideBalloon();
}
}
}
/**
* Sets the onTouchListener for the balloon being displayed, calling the
* overridden {@link #onBalloonTap} method.
*/
private OnTouchListener createBalloonTouchListener() {
return new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
View l = ((View) v.getParent()).findViewById(R.id.balloon_main_layout);
Drawable d = l.getBackground();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int[] states = {android.R.attr.state_pressed};
if (d.setState(states)) {
d.invalidateSelf();
}
return true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
int newStates[] = {};
if (d.setState(newStates)) {
d.invalidateSelf();
}
onBalloonTap(currentFocussedIndex, currentFocussedItem);
return true;
} else {
return false;
}
}
};
}
}
BalloonOverlayView.java
/***
* Copyright (c) 2010 readyState Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.androidhive.googlemaps;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.maps.OverlayItem;
/**
* A view representing a MapView marker information balloon.
* <p>
* This class has a number of Android resource dependencies:
* <ul>
* <li>drawable/balloon_overlay_bg_selector.xml</li>
* <li>drawable/balloon_overlay_close.png</li>
* <li>drawable/balloon_overlay_focused.9.png</li>
* <li>drawable/balloon_overlay_unfocused.9.png</li>
* <li>layout/balloon_map_overlay.xml</li>
* </ul>
* </p>
*
* @author Jeff Gilfelt
*
*/
public class BalloonOverlayView<Item extends OverlayItem> extends FrameLayout {
private LinearLayout layout;
private TextView title;
private TextView snippet;
/**
* Create a new BalloonOverlayView.
*
* @param context - The activity context.
* @param balloonBottomOffset - The bottom padding (in pixels) to be applied
* when rendering this view.
*/
public BalloonOverlayView(Context context, int balloonBottomOffset) {
super(context);
setPadding(10, 0, 10, balloonBottomOffset);
layout = new LinearLayout(context);
layout.setVisibility(VISIBLE);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.balloon_overlay, layout);
title = (TextView) v.findViewById(R.id.balloon_item_title);
snippet = (TextView) v.findViewById(R.id.balloon_item_snippet);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.NO_GRAVITY;
addView(layout, params);
}
/**
* Sets the view data from a given overlay item.
*
* @param item - The overlay item containing the relevant view data
* (title and snippet).
*/
public void setData(Item item) {
layout.setVisibility(VISIBLE);
if (item.getTitle() != null) {
title.setVisibility(VISIBLE);
title.setText(item.getTitle());
} else {
title.setVisibility(GONE);
}
if (item.getSnippet() != null) {
snippet.setVisibility(VISIBLE);
snippet.setText(item.getSnippet());
} else {
snippet.setVisibility(GONE);
}
}
}
MyOverLay.java
/*
* Read more: http://csie-tw.blogspot.com/2009/06/android-driving-direction-route-path.html
*
*/
package com.androidhive.googlemaps;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
public class MyOverLay extends Overlay
{
private GeoPoint gp1;
private GeoPoint gp2;
private int mRadius=6;
private int mode=0;
private int defaultColor;
private String text="";
private Bitmap img = null;
public MyOverLay(GeoPoint gp1,GeoPoint gp2,int mode) // GeoPoint is a int. (6E)
{
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
defaultColor = 999; // no defaultColor
}
public MyOverLay(GeoPoint gp1,GeoPoint gp2,int mode, int defaultColor)
{
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
this.defaultColor = defaultColor;
}
public void setText(String t)
{
this.text = t;
}
public void setBitmap(Bitmap bitmap)
{
this.img = bitmap;
}
public int getMode()
{
return mode;
}
@Override
public boolean draw
(Canvas canvas, MapView mapView, boolean shadow, long when)
{
Projection projection = mapView.getProjection();
if (shadow == false)
{
Paint paint = new Paint();
paint.setAntiAlias(true);
Point point = new Point();
projection.toPixels(gp1, point);
// mode=1¡Gstart
if(mode==1)
{
if(defaultColor==999)
paint.setColor(Color.BLUE);
else
paint.setColor(defaultColor);
RectF oval=new RectF(point.x - mRadius, point.y - mRadius,
point.x + mRadius, point.y + mRadius);
// start point
// canvas.drawOval(oval, paint);
}
// mode=2¡Gpath
else if(mode==2)
{
if(defaultColor==999)
paint.setColor(Color.RED);
else
paint.setColor(defaultColor);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(5);
paint.setAlpha(120);
canvas.drawLine(point.x, point.y, point2.x,point2.y, paint);
}
/* mode=3¡Gend */
else if(mode==3)
{
/* the last path */
if(defaultColor==999)
paint.setColor(Color.GREEN);
else
paint.setColor(defaultColor);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(5);
paint.setAlpha(120);
canvas.drawLine(point.x, point.y, point2.x,point2.y, paint);
RectF oval=new RectF(point2.x - mRadius,point2.y - mRadius,
point2.x + mRadius,point2.y + mRadius);
/* end point */
paint.setAlpha(255);
// canvas.drawOval(oval, paint);
}
/* mode=4¡Gcar */
else if(mode==4)
{
if(defaultColor==999)
paint.setColor(Color.GREEN);
else
paint.setColor(defaultColor);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setTextSize(20);
paint.setAntiAlias(true);
canvas.drawBitmap(img, point2.x, point2.y,paint);
canvas.drawText(this.text, point2.x, point2.y, paint);
// Log.d(TAG, "Draw the text="+this.text+ " at point="+point2.x + "," + point2.y);
}
else if(mode==5)
{
if(defaultColor==999)
paint.setColor(Color.GREEN);
else
paint.setColor(defaultColor);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setTextSize(20);
paint.setAntiAlias(true);
canvas.drawBitmap(img, point2.x, point2.y,paint);
// Log.d(TAG, "Draw the text="+this.text+ " at point="+point2.x + "," + point2.y);
}
}
return super.draw(canvas, mapView, shadow, when);
}
}
MyItemizedOverlay.java
/***
* Copyright (c) 2010 readyState Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.androidhive.googlemaps;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.widget.Toast;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
public class MyItemizedOverlay extends BalloonItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> m_overlays = new ArrayList<OverlayItem>();
private Context c;
public MyItemizedOverlay(Drawable defaultMarker, MapView mapView) {
super(boundCenter(defaultMarker), mapView);
c = mapView.getContext();
}
public void addOverlay(OverlayItem overlay) {
m_overlays.add(overlay);
populate();
}
@Override
protected OverlayItem createItem(int i) {
return m_overlays.get(i);
}
@Override
public int size() {
return m_overlays.size();
}
@Override
protected boolean onBalloonTap(int index, OverlayItem item) {
/*Toast.makeText(c, "LOCATION " + index,
Toast.LENGTH_LONG).show();*/
return true;
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidhive.googlemaps"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" >
</uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<supports-screens android:anyDensity="true" android:xlargeScreens="true" android:resizeable="true" android:smallScreens="true" android:normalScreens="true" android:largeScreens="true"/>
<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>
<uses-library android:name="com.google.android.maps" />
</application>
</manifest>
balloon_overlay.xml
<?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="wrap_content"
android:orientation="horizontal"
android:id="@+id/balloon_main_layout"
android:gravity="center_vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/balloon_inner_layout" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" android:layout_weight="1">
<TextView android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="@+id/balloon_item_title"
android:textSize="16dip"
android:textColor="#FF000000"></TextView>
<TextView android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="@+id/balloon_item_snippet"
android:textColor="#FF000000"
android:textSize="12dip"></TextView>
</LinearLayout>
</LinearLayout>
Hi! Thala !!! Nice Blog ... Keep it up !!!
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteRed line is not show on my map T^T
DeleteCan you help me ??
Help me please !!
DeleteYou can send your files . please!!
ReplyDelete(file.rar)
Hi
ReplyDeleteI have posted runnable code so kindly check your code.i have tested the above code working properly in my system.
mChronometer = (Chronometer) findViewById(R.id.chronometer);
ReplyDeletein Mainactivity.java Unknown chronometer
how to do in main.xml
Hi Sorry here no need use mChronometer remove this one in main activity
Delete//Chronometer mChronometer;
//mChronometer = (Chronometer) findViewById(R.id.chronometer);
Remove the two line it will work .................
can you give your mail ??
DeleteI can not draw a line.
T^T
Hi,
DeleteThis is my mail id and i will send complete runnable code ASP...
kumar.jkpm@gmail.com