HowTo OnTouch on a paint overlay (Google maps)? - android

I paint a overlay on my Google maps view (closed polygon, filled). But now I don't know how to pop up a toast when I tap on the overlay. The most examples which I found work with marker and looks very different to my code.
Main Activity:
public class BOSLstItemDetail extends MapActivity{
ArrayList<HashMap<String, Object>> boslst;
MapView mapView;
MapController mapcontrol;
GeoPoint p;
Polygon polygon;
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.boslst_item_detail);
String coordinates[] = {"48.098056", "9.788611"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
MapView mapView = (MapView) findViewById(R.id.mapview);
mapcontrol = mapView.getController();
mapcontrol.animateTo(p);
mapcontrol.setZoom(10);
mapView.setBuiltInZoomControls(true);
ArrayList<GeoPoint> points = new ArrayList<GeoPoint>();
try{
InputStream koord = getAssets().open("gps.txt");
if (koord != null) {
InputStreamReader input = new InputStreamReader(koord);
BufferedReader buffreader = new BufferedReader(input);
String line;
while (( line = buffreader.readLine()) != null) {
String[] point_t = line.split(",");
double y = Double.parseDouble(point_t[0]);
double x = Double.parseDouble(point_t[1]);
points.add(new GeoPoint((int)(x*1e6), (int)(y*1e6)));
}
koord.close();
polygon = new Polygon(points);
}
}catch (Exception e) {
Log.e("APP","Failed", e);
}
mapView.getOverlays().clear();
mapView.getOverlays().add(polygon);
mapView.invalidate();
}
}
Polygon.java
public class Polygon extends Overlay {
ArrayList<GeoPoint> geoPoints;
public Polygon(ArrayList<GeoPoint> points){
geoPoints = points;
}
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow){
//Set the color and style
Paint paint = new Paint();
paint.setColor(Color.parseColor("#88ff0000"));
paint.setAlpha(50);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
//Create path and add points
Path path = new Path();
Point firstPoint = new Point();
mapView.getProjection().toPixels(geoPoints.get(0), firstPoint);
path.moveTo(firstPoint.x, firstPoint.y);
for(int i = 1; i < geoPoints.size(); ++i){
Point nextPoint = new Point();
mapView.getProjection().toPixels(geoPoints.get(i), nextPoint);
path.lineTo(nextPoint.x, nextPoint.y);
}
//Close polygon
path.lineTo(firstPoint.x, firstPoint.y);
path.setLastPoint(firstPoint.x, firstPoint.y);
canvas.drawPath(path, paint);
super.draw(canvas, mapView, shadow);
}
}
gps.txt:
9.34669876098644,48.2405319213867
9.36384963989269,48.2296714782715
9.3639497756958,48.2259712219238
9.87827968597418,48.2786293029785
9.87261867523205,48.2822494506837
9.87254810333263,48.2859611511232
9.88368034362787,48.2898597717285
9.8835382461549,48.2972793579102
9.72781181335461,47.9827613830566
9.72225093841558,47.9826812744141
9.72232818603527,47.9789619445801
9.71129894256597,47.9750900268555
9.70574092864985,47.9750099182129
9.70557022094732,47.9824409484864
9.69992923736572,47.9860801696778
9.69436073303234,47.9860000610352
9.33546066284174,48.2403602600099
9.34669876098644,48.2405319213867

If you're extending Overlay, you can override the OnTap method:
protected boolean onTap(final int index)
{
OverlayItem item = mOverlays.get(index);
if(item != null){
Toast.makeText(mContext, textToShow, Toast.LENGTH_SHORT).show();
}
//return true to indicate we've taken care of it
return true;
}

Related

Overlays not showing up on MapView

So I have my mapview set up, and everything runs, but the overlays don't show up on the map. Any suggestions or help at all would be greatly appreciated.
My MapActivity extension class is the following:
public class trailInformation extends MapActivity {
public String trailName = "";
public loadMapDataTask mapTask = new loadMapDataTask();
public myObject inp = new myObject();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trail_info_layout);
// General variable declarations
Intent intent = getIntent();
trailName = intent.getStringExtra(trailsActivity.EXTRA_MESSAGE);
// Sets map to satellite
final MapView map = (MapView) findViewById(R.id.infoMapView);
map.setSatellite(true);
// Setup map input
inp.setID(R.raw.nordhoff_peak_loop);
inp.setName("mapfile");
inp.setMap(map);
// Display Trail Name
Typeface font = Typeface.createFromAsset(getAssets(), "arial.ttf");
TextView trailNameTV = (TextView) findViewById(R.id.infoTitle);
trailNameTV.setText(trailName);
trailNameTV.setTypeface(font);
Display display = getWindowManager().getDefaultDisplay();
trailNameTV.setTextSize(findTextSize(trailNameTV, trailName,
GalleryPageActivity.getDisplaySize(display).x, font));
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
mapTask.execute(inp);
}
public class loadMapDataTask extends AsyncTask<myObject, Void, File> {
#Override
protected File doInBackground(myObject... params) {
File file = getApplicationContext().getFileStreamPath(
params[0].getName());
if (file.exists()) {
return file;
}
InputStream is;
FileOutputStream fos;
try {
is = getResources().openRawResource(params[0].getID());
byte[] buffer = new byte[is.available()];
is.read(buffer);
fos = openFileOutput(params[0].getName(), MODE_PRIVATE);
fos.write(buffer);
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
List<Location> gpsPoints = XMLParser.getPoints(file);
int i = 0;
int index = 0;
GeoPoint[] geoPoints = new GeoPoint[gpsPoints.size()];
ListIterator<Location> it = gpsPoints.listIterator();
while (it.hasNext()) {
index = it.nextIndex();
Location loc = gpsPoints.get(index);
geoPoints[i] = new GeoPoint((int) (loc.getLatitude() * 1E6),
(int) (loc.getLongitude() * 1E6));
it.next();
Log.i("DEBUG", "" + geoPoints[i]);
}
if (geoPoints.length > 1) {
mapOverlay[] overlays = new mapOverlay[(geoPoints.length - 1)];
MapController mc = params[0].getMap().getController();
mc.animateTo(geoPoints[0]);
mc.setZoom(17);
for (int z = 0; z < overlays.length; z++) {
List<Overlay> mapOverlays;
mapOverlays = params[0].getMap().getOverlays();
mapOverlays.add(overlays[z]);
}
} else {
Log.i("DEBUG", "Not drawing lines because " + geoPoints.length
+ " points exist in geopoints array.");
}
return file;
}
#Override
protected void onPostExecute(File result) {
Log.i("DEBUG", "Task executed");
}
}
public static String readRawTextFile(Context ctx, int resId) {
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while ((line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
public float findTextSize(TextView tV, String text, float Width,
Typeface font) {
float textSize = 100;
float scaledPx = 0;
float densityMultiplier = getBaseContext().getResources()
.getDisplayMetrics().density;
TextPaint paint = tV.getPaint();
paint.setTypeface(font);
while (textSize > 20) {
scaledPx = textSize * densityMultiplier;
paint.setTextSize(scaledPx);
if (paint.measureText(text) < Width) {
return textSize;
} else {
textSize--;
}
}
return 0;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
And my mapOverlay class is the following:
public class mapOverlay extends Overlay {
private Projection projection;
public mapOverlay(MapView map) {
super();
projection = map.getProjection();
}
public void draw(Canvas canvas, MapView mapv, boolean shadow, GeoPoint gp1,
GeoPoint gp2) {
super.draw(canvas, mapv, shadow);
// Configuring the paint brush
Paint mPaint = new Paint();
mPaint.setDither(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(4);
Point p1 = new Point();
Point p2 = new Point();
Path path1 = new Path();
projection.toPixels(gp1, p1);
projection.toPixels(gp2, p2);
path1.moveTo(p1.x, p1.y);
path1.lineTo(p2.x, p2.y);
canvas.drawPath(path1, mPaint);
}
}
I think I might just be missing something about MapView, and there also might be a problem with my Asynctask since it's my first time using it, but I don't think there is.

path tracing program in android

i want the source code for path tracking program in android.
i see the code in
How to draw a path on a map using kml file?
public void drawPath(NavigationDataSet navSet, int color, MapView mMapView01) {
Log.d(myapp.APP, "map color before: " + color);
// color correction for dining, make it darker
if (color == Color.parseColor("#add331")) color = Color.parseColor("#6C8715");
Log.d(myapp.APP, "map color after: " + color);
Collection overlaysToAddAgain = new ArrayList();
for (Iterator iter = mMapView01.getOverlays().iterator(); iter.hasNext();) {
Object o = iter.next();
Log.d(myapp.APP, "overlay type: " + o.getClass().getName());
if (!RouteOverlay.class.getName().equals(o.getClass().getName())) {
// mMapView01.getOverlays().remove(o);
overlaysToAddAgain.add(o);
}
}
mMapView01.getOverlays().clear();
mMapView01.getOverlays().addAll(overlaysToAddAgain);
String path = navSet.getRoutePlacemark().getCoordinates();
Log.d(myapp.APP, "path=" + path);
if (path != null && path.trim().length() > 0) {
String[] pairs = path.trim().split(" ");
Log.d(myapp.APP, "pairs.length=" + pairs.length);
String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude lngLat[2]=height
Log.d(myapp.APP, "lnglat =" + lngLat + ", length: " + lngLat.length);
if (lngLat.length<3) lngLat = pairs[1].split(","); // if first pair is not transferred completely, take seconds pair //TODO
try {
GeoPoint startGP = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6));
mMapView01.getOverlays().add(new RouteOverlay(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;
if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0 && gp1.getLongitudeE6() > 0
&& gp2.getLatitudeE6() > 0 && gp2.getLongitudeE6() > 0) {
// for GeoPoint, first:latitude, second:longitude
gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6));
if (gp2.getLatitudeE6() != 22200000) {
mMapView01.getOverlays().add(new RouteOverlay(gp1, gp2, 2, color));
Log.d(myapp.APP, "draw:" + gp1.getLatitudeE6() + "/" + gp1.getLongitudeE6() + " TO " + gp2.getLatitudeE6() + "/" + gp2.getLongitudeE6());
}
}
// Log.d(myapp.APP,"pair:" + pairs[i]);
}
//routeOverlays.add(new RouteOverlay(gp2,gp2, 3));
mMapView01.getOverlays().add(new RouteOverlay(gp2, gp2, 3));
} catch (NumberFormatException e) {
Log.e(myapp.APP, "Cannot draw route.", e);
}
}
// mMapView01.getOverlays().addAll(routeOverlays); // use the default color
mMapView01.setEnabled(true);
}
but i am unable to execute the code.
if you donot mind can any once give the entire source code .
thanks.
I have two classes HomeActivity and MyOverlay to draw path in google map
here is HomeActivity :
MapView mapView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.e("Home", " activity created");
mapView = (MapView) findViewById(R.id.mapview);
double src_lat = 28.011022; // the testing source 28.011022,73.323802
double src_long = 73.323802;
double dest_lat = 28.008389; // the testing destination 28.008389,73.33599
double dest_long = 73.33599;
Log.e("Home ", " Strting drawing path");
GeoPoint srcGeoPoint = new GeoPoint((int) (src_lat * 1E6),
(int) (src_long * 1E6));
GeoPoint destGeoPoint = new GeoPoint((int) (dest_lat * 1E6),
(int) (dest_long * 1E6));
Log.e("Home ", " Strting drawing path");
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.darkgreen_marker);
mapView.getOverlays();
OverlayItem overlayitem = new OverlayItem(srcGeoPoint, "Hello!", "This is your position");
overLay marker_overlay=new overLay(drawable);
marker_overlay.addOverlay(overlayitem);
mapOverlays.add(marker_overlay);
overlayitem = new OverlayItem(destGeoPoint, "Theater Big ", "Go to this ");
marker_overlay.addOverlay(overlayitem);
mapOverlays.add(marker_overlay);
//mapView.getOverlays().add(new overLay(null, destGeoPoint));
DrawPath(srcGeoPoint, destGeoPoint, Color.GREEN, mapView);
mapView.getController().animateTo(srcGeoPoint);
mapView.getController().setZoom(15);
mapView.setBuiltInZoomControls(true);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
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.e("Draw path ","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());
Log.e(" Home ", " response"+doc.toString());
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("draw path ","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("Draw path","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();
}
}
public class overLay extends ItemizedOverlay<OverlayItem>{
private List<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
GeoPoint gp1;
Drawable marker;
public overLay(Drawable marker) {
super(marker);
this.marker=marker;
}
public void addOverlay(OverlayItem overlay){
mOverlays.add(overlay);
Log.e(" Map Overlay __", " adding new item "+overlay);
populate();
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when){
Projection projection = mapView.getProjection();
Point point = new Point();
for(int i=0;i<mOverlays.size();i++){
OverlayItem g = getItem(i);
gp1=g.getPoint();
projection.toPixels(gp1, point);
Bitmap bmp = BitmapFactory.decodeResource(
getResources(), R.drawable.marker_red);
canvas.drawBitmap(bmp, point.x-10, point.y-35, null);
}
return super.draw(canvas, mapView, shadow, when);
}
#Override
public boolean onTap(int index){
/* GeoPonit p MapView mapView*/
OverlayItem item = getItem(index);
GeoPoint gp=item.getPoint();
String msg=item.getSnippet();
mapView.getController().animateTo(gp);
Log.e("-- map view --", " marker clicked "+gp);
LayoutInflater infalter=getLayoutInflater();
final LinearLayout table = (LinearLayout)infalter.inflate(R.layout.popup_baloon_layout, null);
table.setWillNotDraw(false);
final MapView.LayoutParams lp2 = new MapView.LayoutParams(
150,100,gp,-15,-10,MapView.LayoutParams.BOTTOM_CENTER);
TextView addrs=(TextView)table.findViewById(R.id.address);
addrs.setText(msg);
ImageView call_img=(ImageView)table.findViewById(R.id.imageView1);
call_img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("__ Home __", " making call to 12345");
Bundle bundle=new Bundle();
mapView.removeView(table);
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + bundle.getString("12345")));
HomeActivity.this.startActivity(intent);
}
});
table.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mapView.removeView(table);
//table=null;
}
});
mapView.addView(table,lp2);
return true;
}
#Override
protected OverlayItem createItem(int i) {
Log.e("Map Overlay __", " creating overlay item "+i);
return mOverlays.get(i);
}
#Override
public int size() {
Log.e("Map Overlay __", " getting overlay size ");
return mOverlays.size();
}
}
and MyOverLay class :
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;
private Context context;
public MyOverLay(GeoPoint gp1,GeoPoint gp2,int mode,Context context){// GeoPoint is a int. (6E)
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
defaultColor = 999; // no defaultColor
this.context=context;
}
public MyOverLay(GeoPoint gp1,GeoPoint gp2,int mode, int defaultColor,Context context){
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
this.defaultColor = defaultColor;
this.context=context;
}
/*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:start
if(mode==1){
if(defaultColor==999)
paint.setColor(Color.BLUE);
else
paint.setColor(defaultColor);
Bitmap bmp = BitmapFactory.decodeResource(
context.getResources(), R.drawable.marker_red);
canvas.drawBitmap(bmp, point.x-10, point.y-35, null);
/*RectF oval=new RectF(point.x - mRadius, point.y - mRadius,
point.x + mRadius, point.y + mRadius);*/
// start point
//canvas.drawOval(oval, paint);
}
// mode=2:path
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:end */
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);
Bitmap bmp = BitmapFactory.decodeResource(
context.getResources(), R.drawable.marker_red);
canvas.drawBitmap(bmp, point.x-16, point.y-38, null);
/*RectF oval=new RectF(point2.x - mRadius,point2.y - mRadius,
point2.x + mRadius,point2.y + mRadius);
paint.setAlpha(255);
canvas.drawOval(oval, paint);*/
}
}
return super.draw(canvas, mapView, shadow, when);
}
#Override
public boolean onTap(GeoPoint p, MapView mapView){
return false;
}
}
These classes use kml to draw path between two locations.

How to find optimal route between two points on google map and then highlight it?

Suppose I have two geolocations(points) on google map,now I want to highlight an optimal route between these two points through different cities.How can I do this ? I have searched on internet and found Drawing a line/path on Google Maps but this explains drawing a straight line between two points.I need to find route connecting different cites and at least the places which come in between two points.not a straight line.Can anyone give me some goodd tutorial or some idea how to do that ?
Answer: If any other person is facing same problem please see the accepted answer.To implement optimal route refer to http://csie-tw.blogspot.com/2009/06/android-driving-direction-route-path.html This is an excellent tutorial with working codes.You can modify them according to your need.And one more thing,while testing please give only those coordinates for which paths are possible(mistake that I was doing).Rest is all fine.Go ahead with the codes.Thanks.
go through this codes. Modify the code as per ur requirement
//mapdirection.java
public class mapdirection extends MapActivity{
MapView mapview;
MapRouteOverlay mapoverlay;
Context _context;
List<Overlay> maplistoverlay;
Drawable drawable,drawable2;
MapOverlay mapoverlay2,mapoverlay3;
GeoPoint srcpoint,destpoint;
Overlay overlayitem;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.map_direction);
RegisterActivities.registerActivity(this);
mapview=(MapView)this.findViewById(R.id.mapview);
callMap();
}
private void callMap() {
srcpoint=new GeoPoint((int)(Data.src_lat_date*1E6),(int)(Data.src_long_data*1E6));
maplistoverlay=mapview.getOverlays();
drawable=this.getResources().getDrawable(R.drawable.green_a);
mapoverlay2=new MapOverlay(drawable);
OverlayItem overlayitem = new OverlayItem(srcpoint, "", "");
mapoverlay2.addOverlay(overlayitem);
maplistoverlay.add(mapoverlay2);
destpoint=new GeoPoint((int)(Data.dest_lat_data*1E6),(int)(Data.dest_long_data*1E6));
drawable2=this.getResources().getDrawable(R.drawable.green_b);
mapoverlay3=new MapOverlay(drawable2);
OverlayItem overlayitem3 = new OverlayItem(destpoint, "", "");
mapoverlay3.addOverlay(overlayitem3);
maplistoverlay.add(mapoverlay3);
double dest_lat = Data.dest_lat_data;
double dest_long = Data.dest_long_data;
GeoPoint srcGeoPoint = new GeoPoint((int) (Data.src_lat_date* 1E6),
(int) (Data.src_long_data * 1E6));
GeoPoint destGeoPoint = new GeoPoint((int) (dest_lat * 1E6),
(int) (dest_long * 1E6));
DrawPath(srcGeoPoint, destGeoPoint, Color.BLUE, mapview);
mapview.getController().animateTo(srcGeoPoint);
mapview.getController().setZoom(13);
//mapview.setStreetView(true);
mapview.setBuiltInZoomControls(true);
mapview.invalidate();
}
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());
//System.out.println(urlString);
// 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(overlayitem);
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 MapRouteOverlay(gp1,gp2,2,color));
Log.d("xxx","pair:" + pairs[i]);
}
//mMapView01.getOverlays().add(new MapRouteOverlay(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();
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
//MapRouteOverlay.java
public class MapRouteOverlay extends Overlay {
private GeoPoint gp1;
private GeoPoint gp2;
private int mode=0;
private int defaultColor;
public MapRouteOverlay(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 MapRouteOverlay(GeoPoint gp1,GeoPoint gp2,int mode, int defaultColor)
{
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
this.defaultColor = defaultColor;
}
public int getMode()
{
return mode;
}
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);
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);
}
}
return super.draw(canvas, mapView, shadow, when);
}
}
Yeah its right that am answering this question after long time. But I think this can help any other.
Put this code in onCreate or in your own method.
MapView mv = (MapView)findViewById(R.id.mvGoogle);
mv.setBuiltInZoomControls(true);
MapController mc = mv.getController();
//getDirections(lat1,lon2,lat2,lon2);
ArrayList<GeoPoint> all_geo_points = getDirections(10.154929, 76.390316, 10.015861, 76.341867);
if(all_geo_points.size()>0){
GeoPoint moveTo = all_geo_points.get(0);
mc.animateTo(moveTo);
mc.setZoom(12);
mv.getOverlays().add(new MyOverlay(all_geo_points));
}else {
Toast.makeText(getApplicationContext(), "Not able to show route !!", Toast.LENGTH_LONG).show();
}
Now make your own custom overlay class.
public class MyOverlay extends Overlay {
private ArrayList<GeoPoint> all_geo_points;
public MyOverlay(ArrayList<GeoPoint> allGeoPoints) {
super();
this.all_geo_points = allGeoPoints;
}
#Override
public boolean draw(Canvas canvas, MapView mv, boolean shadow, long when) {
super.draw(canvas, mv, shadow);
drawPath(mv, canvas);
return true;
}
public void drawPath(MapView mv, Canvas canvas) {
int xPrev = -1, yPrev = -1, xNow = -1, yNow = -1;
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(4);
paint.setAlpha(100);
if (all_geo_points != null) for (int i = 0; i < all_geo_points.size() - 4; i++) {
GeoPoint gp = all_geo_points.get(i);
Point point = new Point();
mv.getProjection().toPixels(gp, point);
xNow = point.x;
yNow = point.y;
if (xPrev != -1) {
canvas.drawLine(xPrev, yPrev, xNow, yNow, paint);
}
xPrev = xNow;
yPrev = yNow;
}
}
}
Now this method will give you all GeoPoints to draw route.I'll prefer to put this code in separate AsyncTask.
public static ArrayList<GeoPoint> getDirections(double lat1, double lon1, double lat2, double lon2) {
String url = "http://maps.googleapis.com/maps/api/directions/xml?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2
+ "&sensor=false&units=metric";
String tag[] = {"lat", "lng"};
ArrayList<GeoPoint> list_of_geopoints = new ArrayList<GeoPoint>();
HttpResponse response = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
response = httpClient.execute(httpPost, localContext);
InputStream in = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
if (doc != null) {
NodeList nl1, nl2;
nl1 = doc.getElementsByTagName(tag[0]);
nl2 = doc.getElementsByTagName(tag[1]);
if (nl1.getLength() > 0) {
list_of_geopoints = new ArrayList<GeoPoint>();
for (int i = 0; i < nl1.getLength(); i++) {
Node node1 = nl1.item(i);
Node node2 = nl2.item(i);
double lat = Double.parseDouble(node1.getTextContent());
double lng = Double.parseDouble(node2.getTextContent());
list_of_geopoints.add(new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6)));
}
} else {
// No points found
}
}
} catch (Exception e) {
e.printStackTrace();
}
return list_of_geopoints;
}

to draw route on google maps, android

Hey I'm trying this code to get connected to Google maps by passing source and destination co-ordinates to this URL and receive a KML file. However I'm not able to parse or get connected to this URL.
Can anybody see where I'm going wrong?
public class RoutePath extends MapActivity {
MapView mapView;
GeoPoint gp1,gp2;
MapController mc;
public class MyOverLay extends Overlay {
private int mRadius=6;
private int mode=0;
private int defaultColor;
private String text="";
private Bitmap img = null;
public MyOverLay() {
}
public MyOverLay(GeoPoint p1,GeoPoint p2,int mode) { // GeoPoint is a int. (6E)
gp1 = p1;
gp2 = p2;
this.mode = mode;
defaultColor = 999; // no defaultColor
}
public MyOverLay(GeoPoint p1,GeoPoint p2,int mode, int defaultColor) {
gp1 = p1;
gp2 = p2;
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) {
super.draw(canvas, mapView, shadow);
Point screenPts = new Point();
mapView.getProjection().toPixels(gp1, screenPts);
Bitmap bmp = BitmapFactory.decodeResource(
getResources(), R.drawable.pushpin);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
return true;
}
public boolean onTouchEvent(MotionEvent event, MapView mapView) {
// when user lifts his finger
if (event.getAction() == 1) {
Toast.makeText(getBaseContext(),"Distance", Toast.LENGTH_SHORT).show();
GeoPoint gp2 = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Toast.makeText(getBaseContext(), gp2.getLatitudeE6() / 1E6 + "," + gp2.getLongitudeE6() /1E6 , Toast.LENGTH_SHORT).show();
double src_lat = 19.0552; // the testing source
double src_long = 72.8308;
//double dest_lat = 19.0800; // the testing destination
//double dest_long = 72.8545;
double dest_lat = gp2.getLatitudeE6() / 1E6; // the testing destination
double dest_long = gp2.getLongitudeE6() /1E6;
GeoPoint gp1 = new GeoPoint((int) (src_lat * 1E6),(int) (src_long * 1E6));
DrawPath(gp1, gp2, Color.GREEN, mapView);
}
return true;
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView mapView = (MapView) findViewById(R.id.myMapView1);
LinearLayout zoom = (LinearLayout)findViewById(R.id.myMapView);
View zoomView = mapView.getZoomControls();
double src_lat = 19.0552; // the testing source
double src_long = 72.8308;
gp1 = new GeoPoint(
(int) (src_lat * 1E6),
(int) (src_long * 1E6));
MyOverLay mapOverlay = new MyOverLay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
mc = mapView.getController();
mc.animateTo(gp1);
mc.setZoom(17);
mapView.invalidate();
mapView.getController().animateTo(gp1);
mapView.getController().setZoom(15);
}
private void DrawPath(GeoPoint src,GeoPoint dest, int color, MapView mMapView01) {
//Toast.makeText(getBaseContext(),"Drawpath initialized", Toast.LENGTH_SHORT).show();
// 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");
//Toast.makeText(getBaseContext(),urlString, Toast.LENGTH_LONG).show();
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);
//Toast.makeText(getBaseContext(),"connected", Toast.LENGTH_SHORT).show();
urlConnection.connect();
//Toast.makeText(getBaseContext(),"connected", Toast.LENGTH_SHORT).show();
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();
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return true;
}
}
I have gone through all the suggested links n answers and have come to this stage wherein i am able to calculate distance but can not draw route, all i can get is a straight line between the last two points of the kml file
here is my code.....kindly lemme know how can i overcome this as i have to draw the complete travelling route from source to destination.
public class RoutePath extends MapActivity {
GeoPoint gp1;
GeoPoint gp2;
GeoPoint srcGeoPoint;
GeoPoint destGeoPoint;
double distance;
public class MyOverLay extends com.google.android.maps.Overlay
{
private int mRadius=6;
private int mode=0;
private int defaultColor;
public MyOverLay()
{
}
public MyOverLay(GeoPoint p1,GeoPoint p2,int mode) // GeoPoint is a int. (6E)
{
gp1 = p1;
gp2 = p2;
this.mode = mode;
defaultColor = 999; // no defaultColor
}
public MyOverLay(GeoPoint p1,GeoPoint p2,int mode, int defaultColor)
{
gp1 = p1;
gp2 = p2;
this.mode = mode;
this.defaultColor = defaultColor ;
}
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:start
if(mode==1)
{
if(defaultColor==999)
paint.setColor(Color.RED);
//Toast.makeText(getBaseContext(), "mode1", Toast.LENGTH_SHORT).show();
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:path
if(mode==2)
{
if(defaultColor==999)
paint.setColor(Color.RED);
//Toast.makeText(getBaseContext(), "mode2", Toast.LENGTH_SHORT).show();
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:end */
else if(mode==3)
{
//the last path
if(defaultColor==999)
{paint.setColor(Color.BLUE);
Toast.makeText(getBaseContext(), "mode3", Toast.LENGTH_SHORT).show();}
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);
paint.setAlpha(255);
canvas.drawOval(oval, paint);
}
}
return super.draw(canvas, mapView, shadow, when);
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
//---when user lifts his finger---
if (event.getAction() == 1)
{
GeoPoint destGeoPoint = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Toast.makeText(getBaseContext(),
destGeoPoint.getLatitudeE6() / 1E6 + "," +
destGeoPoint.getLongitudeE6() /1E6 ,
Toast.LENGTH_SHORT).show();
double src_lat = 19.0552; // the testing source
double src_long = 72.8308;
double dest_lat = destGeoPoint.getLatitudeE6() / 1E6; // the testing destination
double dest_long = destGeoPoint.getLongitudeE6() /1E6;
gp1 = new GeoPoint((int) (src_lat * 1E6),(int) (src_long * 1E6));
gp2 = new GeoPoint((int) (dest_lat * 1E6),(int) (dest_long * 1E6));
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
gp2.getLatitudeE6() / 1E6,
gp2.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();
DrawPath(gp1, gp2 , Color.GREEN, mapView);
}
catch (IOException e) {
e.printStackTrace();
}
return true;
}
else
return false;
}
}
/** Called when the activity is first created. */
MapView mapView;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView mapView = (MapView) findViewById(R.id.myMapView1);
mapView.setBuiltInZoomControls(true);
double src_lat = 19.0552; // the testing source
double src_long = 72.8308;
gp1 = new GeoPoint(
(int) (src_lat * 1E6),
(int) (src_long * 1E6));
MyOverLay mapOverlay = new MyOverLay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
mapView.setSatellite(true);
mapView.getController().animateTo(gp1);
mapView.getController().setZoom(15);
}
#Override
protected boolean isRouteDisplayed()
{
// TODO Auto-generated method stub
return true;
}
private void DrawPath(GeoPoint src,GeoPoint dest, int color, MapView mMapView01)
{
double distance1=0;
// 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);
// Toast.makeText(getBaseContext(), "Before Connection", Toast.LENGTH_SHORT).show();
urlConnection.connect();
// Toast.makeText(getBaseContext(), "After Connection", Toast.LENGTH_SHORT).show();
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().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(src,src,1));
GeoPoint gp1;
GeoPoint gp2 = startGP;
//Toast.makeText(getBaseContext(), "Before Connection", Toast.LENGTH_SHORT).show();
for(int i=1;i<pairs.length;i++) // the last one would be crash
{
Location locationA = new Location("Point A");
locationA.setLatitude(startGP.getLatitudeE6()/1E6);
locationA.setLongitude(startGP.getLongitudeE6()/1E6);
lngLat = pairs[i].split(",");
gp1 = gp2;
gp2 = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
mMapView01.getOverlays().add(new MyOverLay(gp1,gp2,2,color));
mMapView01.invalidate();
Location locationB = new Location("Point B");
locationB.setLatitude(gp2.getLatitudeE6()/1E6);
locationB.setLongitude(gp2.getLongitudeE6()/1E6);
distance1 = + locationA.distanceTo(locationB);
Log.d("xxx","pair:" + pairs[i]);
}
distance = distance1/1000;
if(distance<= 5.00)
{Toast.makeText(getBaseContext(), "DISTANCE = "+ distance, Toast.LENGTH_SHORT).show();}
else
{Toast.makeText(getBaseContext(), "Location out of range",Toast.LENGTH_SHORT).show();}
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ParserConfigurationException e)
{
e.printStackTrace();
}
catch (SAXException e)
{
e.printStackTrace();
}
}
}
you must look into following post probably solves your problem
http://www.anddev.org/the_friend_finder_-_mapactivity_using_gps_-_part_i_-_ii-t93.html
Edit: J2ME/Android/BlackBerry - driving directions, route between two locations
This is very descriptive post addressing your problem try solution posted there

Android draw route on a Mapview with twoo POI-s

How i can draw a route on a mapview between two poi-s?
go through this codes. Modify the code as per ur requirement
MapDirection.java:
public class MapDirection extends MapActivity{
MapView mapview;
MapRouteOverlay mapoverlay;
Context _context;
List<Overlay> maplistoverlay;
Drawable drawable,drawable2;
MapOverlay mapoverlay2,mapoverlay3;
GeoPoint srcpoint,destpoint;
Overlay overlayitem;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.map_direction);
RegisterActivities.registerActivity(this);
mapview=(MapView)this.findViewById(R.id.mapview);
callMap();
}
private void callMap() {
srcpoint=new GeoPoint((int)(Data.src_lat_date*1E6),(int)(Data.src_long_data*1E6));
maplistoverlay=mapview.getOverlays();
drawable=this.getResources().getDrawable(R.drawable.green_a);
mapoverlay2=new MapOverlay(drawable);
OverlayItem overlayitem = new OverlayItem(srcpoint, "", "");
mapoverlay2.addOverlay(overlayitem);
maplistoverlay.add(mapoverlay2);
destpoint=new GeoPoint((int)(Data.dest_lat_data*1E6),(int)(Data.dest_long_data*1E6));
drawable2=this.getResources().getDrawable(R.drawable.green_b);
mapoverlay3=new MapOverlay(drawable2);
OverlayItem overlayitem3 = new OverlayItem(destpoint, "", "");
mapoverlay3.addOverlay(overlayitem3);
maplistoverlay.add(mapoverlay3);
double dest_lat = Data.dest_lat_data;
double dest_long = Data.dest_long_data;
GeoPoint srcGeoPoint = new GeoPoint((int) (Data.src_lat_date* 1E6),
(int) (Data.src_long_data * 1E6));
GeoPoint destGeoPoint = new GeoPoint((int) (dest_lat * 1E6),
(int) (dest_long * 1E6));
DrawPath(srcGeoPoint, destGeoPoint, Color.BLUE, mapview);
mapview.getController().animateTo(srcGeoPoint);
mapview.getController().setZoom(13);
//mapview.setStreetView(true);
mapview.setBuiltInZoomControls(true);
mapview.invalidate();
}
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());
//System.out.println(urlString);
// 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(overlayitem);
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 MapRouteOverlay(gp1,gp2,2,color));
Log.d("xxx","pair:" + pairs[i]);
}
//mMapView01.getOverlays().add(new MapRouteOverlay(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();
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
MapRouteOverlay.java:
public class MapRouteOverlay extends Overlay {
private GeoPoint gp1;
private GeoPoint gp2;
private int mode=0;
private int defaultColor;
public MapRouteOverlay(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 MapRouteOverlay(GeoPoint gp1,GeoPoint gp2,int mode, int defaultColor)
{
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
this.defaultColor = defaultColor;
}
public int getMode()
{
return mode;
}
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);
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);
}
}
return super.draw(canvas, mapView, shadow, when);
}
}
MapOverlay.java:
public class MapOverlay extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
public MapOverlay(Drawable _defaultMarker) {
super(boundCenterBottom(_defaultMarker));
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
#Override
public int size() {
return mOverlays.size();
}
}

Categories

Resources