want to draw a line between any two location in android - android

This is my main activity
import java.net.HttpURLConnection;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.os.Bundle;
import android.util.Log;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
public class DrawActivity extends MapActivity {
MapView myMapView = null;
MapController myMC = null;
GeoPoint geoPoint = null;
String pairs[]=null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myMapView = (MapView) findViewById(R.id.mapview);
geoPoint = null;
myMapView.setSatellite(false);
System.out.println("before pairs");
String pairs[] = getDirectionData("Hyderabad","hyderguda");
System.out.println("pairs:"+pairs[1]);
String[] lngLat = pairs[0].split(",");
// STARTING POINT
GeoPoint startGP = new GeoPoint(
(int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double
.parseDouble(lngLat[0]) * 1E6));
myMC = myMapView.getController();
geoPoint = startGP;
myMC.setCenter(geoPoint);
myMC.setZoom(15);
myMapView.getOverlays().add(new DirectionPathOverlay(startGP, startGP));
// NAVIGATE THE PATH
GeoPoint gp1;
GeoPoint gp2 = startGP;
for (int i = 1; i < pairs.length; i++) {
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));
myMapView.getOverlays().add(new DirectionPathOverlay(gp1, gp2));
Log.d("xxx", "pair:" + pairs[i]);
}
// END POINT
myMapView.getOverlays().add(new DirectionPathOverlay(gp2, gp2));
myMapView.getController().animateTo(startGP);
myMapView.setBuiltInZoomControls(true);
myMapView.displayZoomControls(true);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private String[] getDirectionData(String srcPlace, String destPlace) {
String urlString = "http://maps.google.com/maps?f=d&hl=en&saddr="
+ srcPlace + "&daddr=" + destPlace
+ "&ie=UTF8&0&om=0&output=kml";
Log.d("URL", urlString);
Document doc = null;
HttpURLConnection urlConnection = null;
URL url = null;
String pathConent = "";
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());
//The above code "doc" is getting null value so thats why its getting crashed here itself not going further execution and returning as `nullpointerexception`
} catch (Exception e) {
}
NodeList nl = doc.getElementsByTagName("LineString");
for (int s = 0; s < nl.getLength(); s++) {
Node rootNode = nl.item(s);
NodeList configItems = rootNode.getChildNodes();
for (int x = 0; x < configItems.getLength(); x++) {
Node lineStringNode = configItems.item(x);
NodeList path = lineStringNode.getChildNodes();
pathConent = path.item(0).getNodeValue();
}
}
String[] tempContent = pathConent.split(" ");
return tempContent;
}
}
and my another part of code
package com.hands;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
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 DirectionPathOverlay extends Overlay {
private GeoPoint gp1;
private GeoPoint gp2;
public DirectionPathOverlay(GeoPoint gp1, GeoPoint gp2) {
this.gp1 = gp1;
this.gp2 = gp2;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
// TODO Auto-generated method stub
Projection projection = mapView.getProjection();
if (shadow == false) {
Paint paint = new Paint();
paint.setAntiAlias(true);
Point point = new Point();
projection.toPixels(gp1, point);
paint.setColor(Color.BLUE);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(2);
canvas.drawLine((float) point.x, (float) point.y, (float) point2.x,
(float) point2.y, paint);
}
return super.draw(canvas, mapView, shadow, when);
}
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
// TODO Auto-generated method stub
super.draw(canvas, mapView, shadow);
}
}
The above is my complete source code plz help me out from this problem

You are using output=kml, this parameter no longer works. You get the error because this URL now retrieves a webpage not KML file.
This way of extracting the Google Directions from Google by parsing the KML file is no longer available since 27 July 2012 (because Google has changed the structure of retrieving Google Directions, now you can only get it by JSON or XML), it is time to migrate your code to JSON instead of KML.
See the answer in my own question here.

Related

Android google map routing by reading KML

How to draw route path on MapView Google API. I have two ordinates. Please tell options to draw path between these two points
REFER THIS LINK
SharedData.java
package com.agarwal.route;
public class SharedData {
// this is a singleton class that provides a global data share for all of the
// activities and services in the MDWrapper application
private static SharedData instance = null;
private SharedData() {
//randomizeServers();
}
// data to be shared
private String APIKEY = "";
private double src_lat = -1;
private double src_lng = -1;
private double dest_lat = -1;
private double dest_lng = -1;
/**
* #return the aPIKEY
*/
public String getAPIKEY() {
return APIKEY;
}
/**
* #param aPIKEY the aPIKEY to set
*/
public void setAPIKEY(String aPIKEY) {
APIKEY = aPIKEY;
}
/**
* #return the src_lat
*/
public double getSrc_lat() {
return src_lat;
}
/**
* #param src_lat the src_lat to set
*/
public void setSrc_lat(double src_lat) {
this.src_lat = src_lat;
}
/**
* #return the src_lng
*/
public double getSrc_lng() {
return src_lng;
}
/**
* #param src_lng the src_lng to set
*/
public void setSrc_lng(double src_lng) {
this.src_lng = src_lng;
}
/**
* #return the dest_lat
*/
public double getDest_lat() {
return dest_lat;
}
/**
* #param dest_lat the dest_lat to set
*/
public void setDest_lat(double dest_lat) {
this.dest_lat = dest_lat;
}
/**
* #return the dest_lng
*/
public double getDest_lng() {
return dest_lng;
}
/**
* #param dest_lng the dest_lng to set
*/
public void setDest_lng(double dest_lng) {
this.dest_lng = dest_lng;
}
public static SharedData getInstance() {
if (null == instance) {
instance = new SharedData();
}
return instance;
}
}
CustomItemizedOverlay.java
package com.agarwal.route;
import java.util.ArrayList;
import android.graphics.drawable.Drawable;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class CustomItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private final ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
public CustomItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
#Override
protected OverlayItem createItem(int i) {
return mapOverlays.get(i);
}
#Override
public int size() {
return mapOverlays.size();
}
public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
this.populate();
}
}
MyOverLay.java
package com.agarwal.route;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
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 mode=0;
private int defaultColor;
Context mContext;
public MyOverLay(Context context,GeoPoint gp1,GeoPoint gp2,int mode) // GeoPoint is a int. (6E)
{
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
this.mContext = context;
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 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);
// start point
}
// 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);
/* end point */
}
}
return super.draw(canvas, mapView, shadow, when);
}
}
RoutePath.java
package com.agarwal.route;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
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.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class RoutePath extends MapActivity {
/** Called when the activity is first created. */
MapView mapView;
private RoutePath _activity;
GeoPoint srcGeoPoint,destGeoPoint;
private static List<Overlay> mOverlays;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedData data = SharedData.getInstance();
mapView = new MapView(this,data.getAPIKEY());
mapView.setClickable(true);
setContentView(mapView);
_activity = this;
double src_lat = data.getSrc_lat();
double src_long = data.getSrc_lng();
double dest_lat = data.getDest_lat();
double dest_long = data.getDest_lng();
if(src_lat == -1 || src_long == -1 || dest_lat == -1 || dest_long == -1){
showAlert("Please enter source and destination points");
}else{
srcGeoPoint = new GeoPoint((int) (src_lat * 1E6),(int) (src_long * 1E6));
destGeoPoint = new GeoPoint((int) (dest_lat * 1E6),(int) (dest_long * 1E6));
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable srcdrawable = this.getResources().getDrawable(R.drawable.pin_green);
CustomItemizedOverlay srcitemizedOverlay = new CustomItemizedOverlay(srcdrawable);
//CustomItemizedOverlay srcitemizedOverlay = new CustomItemizedOverlay(getDrawable("com/agarwal/route/pin_green.png"));
OverlayItem srcoverlayitem = new OverlayItem(srcGeoPoint, "Hello!", "This is your Location.");
Drawable destdrawable = this.getResources().getDrawable(R.drawable.pin_red);
CustomItemizedOverlay destitemizedOverlay = new CustomItemizedOverlay( destdrawable );
// CustomItemizedOverlay destitemizedOverlay = new CustomItemizedOverlay(getDrawable("com/agarwal/route/pin_red.png"));
OverlayItem destoverlayitem = new OverlayItem(destGeoPoint, "Hello!", "This is dest Location.");
srcitemizedOverlay.addOverlay(srcoverlayitem);
destitemizedOverlay.addOverlay(destoverlayitem);
mapOverlays.add(srcitemizedOverlay);
mapOverlays.add(destitemizedOverlay);
connectAsyncTask _connectAsyncTask = new connectAsyncTask();
_connectAsyncTask.execute();
mapView.setBuiltInZoomControls(true);
mapView.displayZoomControls(true);
mOverlays = mapView.getOverlays();
mapView.getController().animateTo(srcGeoPoint);
mapView.getController().setZoom(12);
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private class connectAsyncTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(_activity);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
fetchData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(doc!=null){
Overlay ol = new MyOverLay(_activity,srcGeoPoint,srcGeoPoint,1);
mOverlays.add(ol);
NodeList _nodelist = doc.getElementsByTagName("status");
Node node1 = _nodelist.item(0);
String _status1 = node1.getChildNodes().item(0).getNodeValue();
if(_status1.equalsIgnoreCase("OK")){
NodeList _nodelist_path = doc.getElementsByTagName("overview_polyline");
Node node_path = _nodelist_path.item(0);
Element _status_path = (Element)node_path;
NodeList _nodelist_destination_path = _status_path.getElementsByTagName("points");
Node _nodelist_dest = _nodelist_destination_path.item(0);
String _path = _nodelist_dest.getChildNodes().item(0).getNodeValue();
List<GeoPoint> _geopoints = decodePoly(_path);
GeoPoint gp1;
GeoPoint gp2;
gp2 = _geopoints.get(0);
Log.d("_geopoints","::"+_geopoints.size());
for(int i=1;i<_geopoints.size();i++) // the last one would be crash
{
gp1 = gp2;
gp2 = _geopoints.get(i);
Overlay ol1 = new MyOverLay(gp1,gp2,2,Color.BLUE);
mOverlays.add(ol1);
}
Overlay ol2 = new MyOverLay(_activity,destGeoPoint,destGeoPoint,3);
mOverlays.add(ol2);
progressDialog.dismiss();
}else{
showAlert("Unable to find the route");
}
Overlay ol2 = new MyOverLay(_activity,destGeoPoint,destGeoPoint,3);
mOverlays.add(ol2);
progressDialog.dismiss();
mapView.scrollBy(-1,-1);
mapView.scrollBy(1,1);
}else{
showAlert("Unable to find the route");
}
}
}
Document doc = null;
private void fetchData()
{
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.google.com/maps/api/directions/xml?origin=");
urlString.append( Double.toString((double)srcGeoPoint.getLatitudeE6()/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)srcGeoPoint.getLongitudeE6()/1.0E6 ));
urlString.append("&destination=");//to
urlString.append( Double.toString((double)destGeoPoint.getLatitudeE6()/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)destGeoPoint.getLongitudeE6()/1.0E6 ));
urlString.append("&sensor=true&mode=driving");
Log.d("url","::"+urlString.toString());
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 = (Document) db.parse(urlConnection.getInputStream());//Util.XMLfromString(response);
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}catch (ParserConfigurationException e){
e.printStackTrace();
}
catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private List<GeoPoint> decodePoly(String encoded) {
List<GeoPoint> poly = new ArrayList<GeoPoint>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
GeoPoint p = new GeoPoint((int) (((double) lat / 1E5) * 1E6),
(int) (((double) lng / 1E5) * 1E6));
poly.add(p);
}
return poly;
}
private void showAlert(String message){
AlertDialog.Builder alert = new AlertDialog.Builder(_activity);
alert.setTitle("Error");
alert.setCancelable(false);
alert.setMessage(message);
alert.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alert.show();
}
private Drawable getDrawable(String fileName){
return Drawable.createFromStream(_activity.getClass().getClassLoader().getResourceAsStream(fileName), "pin");
}
}
In Your Activity Just Paste the below few lines to draw routemap:
SharedData data = SharedData.getInstance();
data.setAPIKEY("0RUTLH7cqd6yrZ0FdS0NfQMO3lioiCbnH-BpNQQ");
data.setSrc_lat(17);
data.setSrc_lng(78);
data.setDest_lat(18);
data.setDest_lng(77);
startActivity(new Intent(YourActivity.this,RoutePath.class));
Note:: Need to RoutePath activity and permssions in your manifeast file
You can refer link Android Driving Direction.
Full description is given there with source that you can download from source link 1 or source link 2

How to draw route between two points in map in Async Task

Hi I'm using the code from below link to draw route between two points in map.
http://code.google.com/p/j2memaprouteprovider/source/browse/#svn/trunk/J2MEMapRouteAndroidEx/src/org/ci/geo/route
Also I'm using timer to update locations dynamically every 30 seconds. It works good. But the application freezes after 20 seconds. After the route is drawn between 2 points app becomes slow while zooming in or zooming out the map.
Is there any other efficient way to draw route between 2 points or in Async task??
Any help Appreciated.
Refer this LINK
SharedData.java
package com.agarwal.route;
public class SharedData {
// this is a singleton class that provides a global data share for all of the
// activities and services in the MDWrapper application
private static SharedData instance = null;
private SharedData() {
//randomizeServers();
}
// data to be shared
private String APIKEY = "";
private double src_lat = -1;
private double src_lng = -1;
private double dest_lat = -1;
private double dest_lng = -1;
/**
* #return the aPIKEY
*/
public String getAPIKEY() {
return APIKEY;
}
/**
* #param aPIKEY the aPIKEY to set
*/
public void setAPIKEY(String aPIKEY) {
APIKEY = aPIKEY;
}
/**
* #return the src_lat
*/
public double getSrc_lat() {
return src_lat;
}
/**
* #param src_lat the src_lat to set
*/
public void setSrc_lat(double src_lat) {
this.src_lat = src_lat;
}
/**
* #return the src_lng
*/
public double getSrc_lng() {
return src_lng;
}
/**
* #param src_lng the src_lng to set
*/
public void setSrc_lng(double src_lng) {
this.src_lng = src_lng;
}
/**
* #return the dest_lat
*/
public double getDest_lat() {
return dest_lat;
}
/**
* #param dest_lat the dest_lat to set
*/
public void setDest_lat(double dest_lat) {
this.dest_lat = dest_lat;
}
/**
* #return the dest_lng
*/
public double getDest_lng() {
return dest_lng;
}
/**
* #param dest_lng the dest_lng to set
*/
public void setDest_lng(double dest_lng) {
this.dest_lng = dest_lng;
}
public static SharedData getInstance() {
if (null == instance) {
instance = new SharedData();
}
return instance;
}
}
CustomItemizedOverlay.java
package com.agarwal.route;
import java.util.ArrayList;
import android.graphics.drawable.Drawable;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class CustomItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private final ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
public CustomItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
#Override
protected OverlayItem createItem(int i) {
return mapOverlays.get(i);
}
#Override
public int size() {
return mapOverlays.size();
}
public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
this.populate();
}
}
MyOverLay.java
package com.agarwal.route;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
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 mode=0;
private int defaultColor;
Context mContext;
public MyOverLay(Context context,GeoPoint gp1,GeoPoint gp2,int mode) // GeoPoint is a int. (6E)
{
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
this.mContext = context;
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 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);
// start point
}
// 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);
/* end point */
}
}
return super.draw(canvas, mapView, shadow, when);
}
}
RoutePath.java
package com.agarwal.route;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
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.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class RoutePath extends MapActivity {
/** Called when the activity is first created. */
MapView mapView;
private RoutePath _activity;
GeoPoint srcGeoPoint,destGeoPoint;
private static List<Overlay> mOverlays;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedData data = SharedData.getInstance();
mapView = new MapView(this,data.getAPIKEY());
mapView.setClickable(true);
setContentView(mapView);
_activity = this;
double src_lat = data.getSrc_lat();
double src_long = data.getSrc_lng();
double dest_lat = data.getDest_lat();
double dest_long = data.getDest_lng();
if(src_lat == -1 || src_long == -1 || dest_lat == -1 || dest_long == -1){
showAlert("Please enter source and destination points");
}else{
srcGeoPoint = new GeoPoint((int) (src_lat * 1E6),(int) (src_long * 1E6));
destGeoPoint = new GeoPoint((int) (dest_lat * 1E6),(int) (dest_long * 1E6));
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable srcdrawable = this.getResources().getDrawable(R.drawable.pin_green);
//CustomItemizedOverlay srcitemizedOverlay = new CustomItemizedOverlay(getDrawable("com/agarwal/route/pin_green.png"));
OverlayItem srcoverlayitem = new OverlayItem(srcGeoPoint, "Hello!", "This is your Location.");
Drawable destdrawable = this.getResources().getDrawable(R.drawable.pin_red);
// CustomItemizedOverlay destitemizedOverlay = new CustomItemizedOverlay(getDrawable("com/agarwal/route/pin_red.png"));
OverlayItem destoverlayitem = new OverlayItem(destGeoPoint, "Hello!", "This is dest Location.");
srcitemizedOverlay.addOverlay(srcoverlayitem);
destitemizedOverlay.addOverlay(destoverlayitem);
mapOverlays.add(srcitemizedOverlay);
mapOverlays.add(destitemizedOverlay);
connectAsyncTask _connectAsyncTask = new connectAsyncTask();
_connectAsyncTask.execute();
mapView.setBuiltInZoomControls(true);
mapView.displayZoomControls(true);
mOverlays = mapView.getOverlays();
mapView.getController().animateTo(srcGeoPoint);
mapView.getController().setZoom(12);
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private class connectAsyncTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(_activity);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
fetchData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(doc!=null){
Overlay ol = new MyOverLay(_activity,srcGeoPoint,srcGeoPoint,1);
mOverlays.add(ol);
NodeList _nodelist = doc.getElementsByTagName("status");
Node node1 = _nodelist.item(0);
String _status1 = node1.getChildNodes().item(0).getNodeValue();
if(_status1.equalsIgnoreCase("OK")){
NodeList _nodelist_path = doc.getElementsByTagName("overview_polyline");
Node node_path = _nodelist_path.item(0);
Element _status_path = (Element)node_path;
NodeList _nodelist_destination_path = _status_path.getElementsByTagName("points");
Node _nodelist_dest = _nodelist_destination_path.item(0);
String _path = _nodelist_dest.getChildNodes().item(0).getNodeValue();
List<GeoPoint> _geopoints = decodePoly(_path);
GeoPoint gp1;
GeoPoint gp2;
gp2 = _geopoints.get(0);
Log.d("_geopoints","::"+_geopoints.size());
for(int i=1;i<_geopoints.size();i++) // the last one would be crash
{
gp1 = gp2;
gp2 = _geopoints.get(i);
Overlay ol1 = new MyOverLay(gp1,gp2,2,Color.BLUE);
mOverlays.add(ol1);
}
Overlay ol2 = new MyOverLay(_activity,destGeoPoint,destGeoPoint,3);
mOverlays.add(ol2);
progressDialog.dismiss();
}else{
showAlert("Unable to find the route");
}
Overlay ol2 = new MyOverLay(_activity,destGeoPoint,destGeoPoint,3);
mOverlays.add(ol2);
progressDialog.dismiss();
mapView.scrollBy(-1,-1);
mapView.scrollBy(1,1);
}else{
showAlert("Unable to find the route");
}
}
}
Document doc = null;
private void fetchData()
{
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.google.com/maps/api/directions/xml?origin=");
urlString.append( Double.toString((double)srcGeoPoint.getLatitudeE6()/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)srcGeoPoint.getLongitudeE6()/1.0E6 ));
urlString.append("&destination=");//to
urlString.append( Double.toString((double)destGeoPoint.getLatitudeE6()/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)destGeoPoint.getLongitudeE6()/1.0E6 ));
urlString.append("&sensor=true&mode=driving");
Log.d("url","::"+urlString.toString());
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 = (Document) db.parse(urlConnection.getInputStream());//Util.XMLfromString(response);
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}catch (ParserConfigurationException e){
e.printStackTrace();
}
catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private List<GeoPoint> decodePoly(String encoded) {
List<GeoPoint> poly = new ArrayList<GeoPoint>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
GeoPoint p = new GeoPoint((int) (((double) lat / 1E5) * 1E6),
(int) (((double) lng / 1E5) * 1E6));
poly.add(p);
}
return poly;
}
private void showAlert(String message){
AlertDialog.Builder alert = new AlertDialog.Builder(_activity);
alert.setTitle("Error");
alert.setCancelable(false);
alert.setMessage(message);
alert.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alert.show();
}
private Drawable getDrawable(String fileName){
return Drawable.createFromStream(_activity.getClass().getClassLoader().getResourceAsStream(fileName), "pin");
}
}
In Your Activity Just Paste the below few lines to draw routemap:
SharedData data = SharedData.getInstance();
data.setAPIKEY("0RUTLH7cqd6yrZ0FdS0NfQMO3lioiCbnH-BpNQQ");
data.setSrc_lat(17);
data.setSrc_lng(78);
data.setDest_lat(18);
data.setDest_lng(77);
startActivity(new Intent(YourActivity.this,RoutePath.class));
Note:: Need to RoutePath activity and permssions in your manifeast file

Accurate paths on Google maps

I have a complicated problem with google maps.I am using android and i draw a path between 2 specific points but the problem is that the path is not accurate because it draw on reversible streets so the path now is not right can anyone have any idea how to ignore the wrong streets??
this is working example link. check it out. it helps to create the route overlay on the map. here is the complete source code for that.
EDIT:
as AlexAndro mentions below: "This method, using kml seems that is not available any more, this issue has been discussed on Stackoverflow in the last days. Google Maps output=kml broken? "
Use the below class code::
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
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.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class RoutePath extends MapActivity {
/** Called when the activity is first created. */
MapView mapView;
private RoutePath _activity;
GeoPoint srcGeoPoint,destGeoPoint;
private static List<Overlay> mOverlays;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
_activity = this;
MapView mapView = (MapView) findViewById(R.id.mapview);
double src_lat = SRCLAT;
double src_long = SRCLNG;
double dest_lat = DESTLAT;
double dest_long = DESTLNG;
srcGeoPoint = new GeoPoint((int) (src_lat * 1E6),(int) (src_long * 1E6));
destGeoPoint = new GeoPoint((int) (dest_lat * 1E6),(int) (dest_long * 1E6));
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable srcdrawable = this.getResources().getDrawable(R.drawable.pin_green);
CustomItemizedOverlay srcitemizedOverlay = new CustomItemizedOverlay(srcdrawable, this);
OverlayItem srcoverlayitem = new OverlayItem(srcGeoPoint, "Hello!", "This is your Location.");
Drawable destdrawable = this.getResources().getDrawable(R.drawable.pin_red);
CustomItemizedOverlay destitemizedOverlay = new CustomItemizedOverlay(destdrawable, this);
OverlayItem destoverlayitem = new OverlayItem(destGeoPoint, "Hello!", "This is dest Location.");
srcitemizedOverlay.addOverlay(srcoverlayitem);
destitemizedOverlay.addOverlay(destoverlayitem);
mapOverlays.add(srcitemizedOverlay);
mapOverlays.add(destitemizedOverlay);
connectAsyncTask _connectAsyncTask = new connectAsyncTask();
_connectAsyncTask.execute();
mapView.setBuiltInZoomControls(true);
mapView.displayZoomControls(true);
mOverlays = mapView.getOverlays();
mapView.getController().animateTo(srcGeoPoint);
mapView.getController().setZoom(12);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private class connectAsyncTask extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
SHOW YOU PROGRESS BAR HERE
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
fetchData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(doc!=null){
Overlay ol = new MyOverLay(_activity,srcGeoPoint,srcGeoPoint,1);
mOverlays.add(ol);
NodeList _nodelist = doc.getElementsByTagName("status");
Node node1 = _nodelist.item(0);
String _status1 = node1.getChildNodes().item(0).getNodeValue();
if(_status1.equalsIgnoreCase("OK")){
NodeList _nodelist_path = doc.getElementsByTagName("overview_polyline");
Node node_path = _nodelist_path.item(0);
Element _status_path = (Element)node_path;
NodeList _nodelist_destination_path = _status_path.getElementsByTagName("points");
Node _nodelist_dest = _nodelist_destination_path.item(0);
String _path = _nodelist_dest.getChildNodes().item(0).getNodeValue();
List<GeoPoint> _geopoints = decodePoly(_path);
GeoPoint gp1;
GeoPoint gp2;
gp2 = _geopoints.get(0);
for(int i=1;i<_geopoints.size();i++) // the last one would be crash
{
gp1 = gp2;
gp2 = _geopoints.get(i);
Overlay ol1 = new MyOverLay(gp1,gp2,2,Color.BLUE);
mOverlays.add(ol1);
}
Overlay ol2 = new MyOverLay(_activity,destGeoPoint,destGeoPoint,3);
mOverlays.add(ol2);
DISMISS PROGRESS BAR HERE
}else{
showAlert AS "Unable to find the route"
}
Overlay ol2 = new MyOverLay(_activity,destGeoPoint,destGeoPoint,3);
mOverlays.add(ol2);
DISMISS PROGRESS BAR HERE
}else{
showAlert AS "Unable to find the route"
}
}
}
Document doc = null;
private void fetchData()
{
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.google.com/maps/api/directions/xml?origin=");
urlString.append( Double.toString((double)srcGeoPoint.getLatitudeE6()/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)srcGeoPoint.getLongitudeE6()/1.0E6 ));
urlString.append("&destination=");//to
urlString.append( Double.toString((double)destGeoPoint.getLatitudeE6()/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)destGeoPoint.getLongitudeE6()/1.0E6 ));
urlString.append("&sensor=true&mode=driving");
if(Constants.LOG)Log.d("xxx","URL="+urlString.toString());
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 = (Document) db.parse(urlConnection.getInputStream());//Util.XMLfromString(response);
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}catch (ParserConfigurationException e){
e.printStackTrace();
}
catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private List<GeoPoint> decodePoly(String encoded) {
List<GeoPoint> poly = new ArrayList<GeoPoint>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
GeoPoint p = new GeoPoint((int) (((double) lat / 1E5) * 1E6),
(int) (((double) lng / 1E5) * 1E6));
poly.add(p);
}
return poly;
}
}
CustomItemizedOverlay.java
import java.util.ArrayList;
import android.content.Context;
import android.graphics.drawable.Drawable;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class CustomItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private final ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
private Context context;
public CustomItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public CustomItemizedOverlay(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();
}
public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
this.populate();
}
}
MyOverLay.java
import android.content.Context;
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 android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
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;
Context mContext;
public MyOverLay(Context context,GeoPoint gp1,GeoPoint gp2,int mode) // GeoPoint is a int. (6E)
{
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
this.mContext = context;
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:start
if(mode==1)
{
if(defaultColor==999)
paint.setColor(Color.BLUE);
else
paint.setColor(defaultColor);
// start point
}
// 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);
/* end point */
}
}
return super.draw(canvas, mapView, shadow, when);
}
}

Can we call MapView Inside an layout

one of the the blogger has given an wonderful idea of calling MapView class inside an application.
turn by turn directions in MapView
the code is
showDirections.setOnClickListener(new View.OnClickListener() {
public void onClick(final View view) {
final Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(
"http://maps.google.com/maps?" +
"saddr=43.0054446,-87.9678884" +
"&daddr=42.9257104,-88.0508355"));
intent.setClassName(
"com.google.android.apps.maps",
"com.google.android.maps.MapsActivity");
startActivity(intent);
}
});
Is it possible to attach this Mapview to a layout, so that it opens with in the layout of our application. As this method opens outside our layout and application. I am looking to fix this MapView to a layout.Any code examples.Looking forward to your reply.thanks
I am writing answer to my own question and got help from other StackOverflow users.
This is full source code to draw direction path from source latitude and longitude to destination latitude and longitude.
So anyone who is accessing his latitude and longitude through his gps can get the direction from his gps device to the destination coordinates.
StackOverflow had an answer and I have changed to latitude and longitude rather than source and destination places.
stack overflow link for route path between source and destination
Thanks to above answers we could make such a change and get path direction.
public class DrawMapActivity extends MapActivity {
MapView myMapView = null;
MapController myMC = null;
GeoPoint geoPoint = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myMapView = (MapView) findViewById(R.id.mapview);
geoPoint = null;
myMapView.setSatellite(false);
double fromLat = 12.303534;
double fromLong = 76.64611;
double toLat = 12.9715987;
double toLong = 77.5945627;
String sourceLat = Double.toString(fromLat);
String sourceLong = Double.toString(fromLong);
String destinationLat = Double.toString(toLat);
String destinationLong = Double.toString(toLong);
String pairs[] = getDirectionData(sourceLat,sourceLong, destinationLat, destinationLong );
String[] lngLat = pairs[0].split(",");
// STARTING POINT
GeoPoint startGP = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6));
myMC = myMapView.getController();
geoPoint = startGP;
myMC.setCenter(geoPoint);
myMC.setZoom(10);
myMapView.getOverlays().add(new DirectionPathOverlay(startGP, startGP));
// NAVIGATE THE PATH
GeoPoint gp1;
GeoPoint gp2 = startGP;
for (int i = 1; i < pairs.length; i++) {
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));
myMapView.getOverlays().add(new DirectionPathOverlay(gp1, gp2));
Log.d("xxx", "pair:" + pairs[i]);
}
// END POINT
myMapView.getOverlays().add(new DirectionPathOverlay(gp2, gp2));
myMapView.getController().animateTo(startGP);
myMapView.setBuiltInZoomControls(true);
myMapView.displayZoomControls(true);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private String[] getDirectionData(String sourceLat, String sourceLong, String destinationLat, String destinationLong) {
String urlString = "http://maps.google.com/maps?f=d&hl=en&" +"saddr="+sourceLat+","+sourceLong+"&daddr="+destinationLat+","+destinationLong + "&ie=UTF8&0&om=0&output=kml";
Log.d("URL", urlString);
Document doc = null;
HttpURLConnection urlConnection = null;
URL url = null;
String pathConent = "";
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());
} catch (Exception e) {
}
NodeList nl = doc.getElementsByTagName("LineString");
for (int s = 0; s < nl.getLength(); s++) {
Node rootNode = nl.item(s);
NodeList configItems = rootNode.getChildNodes();
for (int x = 0; x < configItems.getLength(); x++) {
Node lineStringNode = configItems.item(x);
NodeList path = lineStringNode.getChildNodes();
pathConent = path.item(0).getNodeValue();
}
}
String[] tempContent = pathConent.split(" ");
return tempContent;
}
}
//*****************************************************************************
class DirectionPathOverlay extends Overlay {
private GeoPoint gp1;
private GeoPoint gp2;
public DirectionPathOverlay(GeoPoint gp1, GeoPoint gp2) {
this.gp1 = gp1;
this.gp2 = gp2;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
// TODO Auto-generated method stub
Projection projection = mapView.getProjection();
if (shadow == false) {
Paint paint = new Paint();
paint.setAntiAlias(true);
Point point = new Point();
projection.toPixels(gp1, point);
paint.setColor(Color.BLUE);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(2);
canvas.drawLine((float) point.x, (float) point.y, (float) point2.x,(float) point2.y, paint);
}
return super.draw(canvas, mapView, shadow, when);
}
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
// TODO Auto-generated method stub
super.draw(canvas, mapView, shadow);
}
}
Hope it helps for other Stack Overflow users

Google Maps Api Directions

Can i mark two points on the google maps in my application and then calculate the direction on the map as well as turn by turn navigation ?
I am create an application which are used to get the driving direction between two points in the map
Step be step
step1 First create a class MyOverlay.java which are used to draw a path
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 android.util.Log;
//import android.util.Log;
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);
}
}
step 2: Create a class name DrivingDirectionActivity.java
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.os.Bundle;
import android.util.Log;
import com.android.code.R;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
/**
* #author ashish
*
*
*
*/
public class DrivingDirectionActivity extends MapActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.google_map_driving_direction_view);
MapView mapView = (MapView) findViewById(R.id.myMapView1);
double src_lat = 28.632808;
double src_long = 77.218276;
double dest_lat = 28.588535;
double dest_long = 77.255130;
GeoPoint srcGeoPoint = new GeoPoint((int) (src_lat * 1E6),
(int) (src_long * 1E6));
GeoPoint destGeoPoint = new GeoPoint((int) (dest_lat * 1E6),
(int) (dest_long * 1E6));
DrawPath(srcGeoPoint, destGeoPoint, Color.GREEN, mapView);
mapView.getController().animateTo(srcGeoPoint);
mapView.getController().setZoom(15);
}
/* (non-Javadoc)
* #see com.google.android.maps.MapActivity#isRouteDisplayed()
*/
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private void DrawPath(GeoPoint src, GeoPoint dest, int color,MapView mMapView01) {
// connect to map web service
Document doc = getDocument(makeUrl(src,dest));
System.out.println(doc.toString());
try {
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 ( Exception e) {
e.printStackTrace();
}
}
private Document getDocument(String urlString) {
// TODO Auto-generated method stub
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());
} catch (Exception e) {
// TODO: handle exception
}
return doc;
}
private String makeUrl(GeoPoint src, GeoPoint dest) {
// TODO Auto-generated method stub
// get the kml (XML) doc. And parse it to get the coordinates(direction
// route).
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());
return urlString.toString();
}
}
now execute..
If this is not good then you can pass the your current location as source loaction
No the Map Activity doesn't provide such a feature. You have to request it via the Google Maps Web API.

Categories

Resources