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();
}
}
Related
I'm trying to create a mapView centered in a point previously chosen.
I want to create a route between this point and the device's current position.
Can you help me? Perhaps posting tutorials or examples?
Thank you!
You can download a kml file with the path between two points with this code:
public static Document getKml(GeoPoint src, GeoPoint dest) {
// 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).
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();
return db.parse(urlConnection.getInputStream());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
Then ip's up to you to parse it and display it on a Map ;-)
Hint:
if (doc != null
&& 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
Refer this example
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();
}
}
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.
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
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;
}
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