i have a situation in my app where i should move my map from one location to another location....i am quite new to android..and i found out how to draw a line in between two locations..
public class Mapview extends MapActivity implements LocationListener{
MapController mc;
GeoPoint p,p1,p2;
LocationManager lm;
String provider;
class Mapoverlay extends com.google.android.maps.Overlay
{
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
// TODO Auto-generated method stub
super.draw(canvas, mapView, shadow);
Point screenpoints=new Point();
Point screenpoints1=new Point();
Point screenpoints2=new Point();
Paint paint;
paint = new Paint();
paint.setColor(Color.RED);
paint.setAntiAlias(true);
paint.setStyle(Style.FILL);
paint.setStrokeWidth(2);
paint.setAlpha(120);
Paint paint1;
paint1 = new Paint();
paint1.setColor(Color.BLUE);
paint1.setAntiAlias(true);
paint1.setStyle(Style.FILL);
paint1.setStrokeWidth(2);
paint1.setAlpha(120);
if(p != null)
{
mapView.getProjection().toPixels(p, screenpoints);
mapView.getProjection().toPixels(p1, screenpoints1);
mapView.getProjection().toPixels(p2, screenpoints2);
// Bitmap map=BitmapFactory.decodeResource(getResources(), R.drawable.pushpin1);
// canvas.drawBitmap(map, screenpoints.x, screenpoints.y-53, null);
canvas.drawLine(screenpoints.x,screenpoints.y,screenpoints1.x,screenpoints1.y, paint);
canvas.drawLine(screenpoints.x,screenpoints.y,screenpoints2.x,screenpoints2.y, paint);
}
return true;
}
}
#Override
protected void onCreate(Bundle icicle) {
// TODO Auto-generated method stub
super.onCreate(icicle);
setContentView(R.layout.mapview);
MapView map=(MapView)findViewById(R.id.mapView);
map.setBuiltInZoomControls(true);
mc=map.getController();
String[] coordinates={"51.4750766129036", "-3.15672342166522"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p=new GeoPoint((int)(lat*1E6), (int)(lng*1E6));
String[] coordinates1={"17.453117" , "78.467586" };
double lat1 = Double.parseDouble(coordinates1[0]);
double lng1 = Double.parseDouble(coordinates1[1]);
p2=new GeoPoint((int)(lat1*1E6), (int)(lng1*1E6));
p1 = new GeoPoint(19240000,-99120000);
// p = new GeoPoint(19241000,-99121000);
lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider=lm.getBestProvider(criteria, true);
Location loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
List<String> lists=lm.getAllProviders();
// float f=loc.distanceTo(loc);
if (loc!=null){
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(loc);
}else{
Toast.makeText(getApplicationContext(), "Provider " + provider+ loc + lists+" has not been selected.", 5000).show();
// this.finish();
}
// Toast.makeText(getApplicationContext(), p.getLatitudeE6()+p.getLongitudeE6(), Toast.LENGTH_SHORT).show();
mc.animateTo(p);
mc.setZoom(1);
map.invalidate();
Mapoverlay mapOverlay = new Mapoverlay();
List<Overlay> listOfOverlays = map.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
}
i am stuck at moving map from one location to another without user activity
for example:when the app initiates location of newyork city is shown then the map should move to texas ...any help willl be grateful
Try This class just pass Activity act,GeoPoint src,GeoPoint dest, int color, MapView mMapView
To call this class do this
new getRoute().DrawPath(this,mGeoPoint,getGeoPoint,Color.RED,mMapView);
public class getRoute
{
/*Variable*/
double mIntentLatitude, mIntentLongitude;
double mCursorLatitude, mCursorLongitude, mStartLatitude, mStartLongitude, mEndLatitude, MEndLongitude;
String mJsonData;
String mEnd_Address, mStart_Address, mName;
int mLength;
GeoPoint mGeoPoint = new GeoPoint(220328269, 725588202);
double mLatitude_End[], mLongitude_End[], mLatitude_Start[], mLongitude_Start[];
Activity activity;
public getRoute
(){
}
boolean error = false;
public void DrawPath(Activity act,GeoPoint src,GeoPoint dest, int color, MapView mMapView01)
{
// connect to map web service
DrawPathBack draw = new DrawPathBack(act, src, dest, color, mMapView01);
draw.execute("Draw");
}
public class DrawPathBack extends AsyncTask<String, Integer,Void>
{
ProgressDialog bar;
List<Overlay> mListOverlay;
MapOverlay mapOverlay;
ItemizedOverlay<OverlayItem> mItemizedOverlay;
GeoPoint src,dest;
int color;
MapView mMapView;
CommonMethod mCommonMethod;
String [] pairs;
String[] lngLat;
public DrawPathBack(Activity act,GeoPoint gpsrc,GeoPoint gpdest, int c, MapView mMap)
{
activity =act;
src=gpsrc;
dest=gpdest;
color = c;
mMapView=mMap;
mListOverlay = mMapView.getOverlays();
mapOverlay = new MapOverlay(mGeoPoint);
mListOverlay.add(mapOverlay);
mMapView.invalidate();
}
#Override
protected Void doInBackground(String... params)
{
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(httpParameters, 60000);
HttpClient client = new DefaultHttpClient();
try {
HttpPost httpPost = new HttpPost("http://maps.googleapis.com/maps/api/directions/json?origin="+ (Double.toString((double)src.getLatitudeE6()/1.0E6)) + "," +(Double.toString((double)src.getLongitudeE6()/1.0E6 ) + "&destination=" + (Double.toString((double)dest.getLatitudeE6()/1.0E6)) + ","+ (Double.toString((double)dest.getLongitudeE6()/1.0E6))+ "&sensor=false"));
mIntentLatitude=((double)src.getLatitudeE6()/1.0E6);
mIntentLongitude=((double)src.getLongitudeE6()/1.0E6);
//httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = client.execute(httpPost);
mJsonData = EntityUtils.toString(httpResponse.getEntity());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress)
{
bar.setMessage("Time Progress "+progress[0]);
}
#Override
protected void onPostExecute(Void result)
{
try {
JSONObject jsonObj = new JSONObject(mJsonData);
// grabbing the routes object
JSONArray routes = jsonObj.getJSONArray("routes");
for (int i = 0; i < routes.length(); i++) {
JSONObject rout = routes.getJSONObject(i);
JSONObject bounds = rout.getJSONObject("bounds");
JSONObject northest = bounds.getJSONObject("northeast");
mStartLatitude = northest.getDouble("lat");
mStartLongitude = northest.getDouble("lng");
JSONObject southwest = bounds.getJSONObject("southwest");
mEndLatitude = southwest.getDouble("lat");
MEndLongitude = southwest.getDouble("lng");
System.out.println("get data from jeson" + mCursorLatitude + mCursorLongitude + mEndLatitude
+ MEndLongitude);
// grabbing the routes legs
JSONArray legs = rout.getJSONArray("legs");
System.out.println("length of legs array " + legs.length());
for (int j = 0; j < legs.length(); j++) {
JSONObject leg = legs.getJSONObject(j);
System.out.println("enter in second array");
JSONObject distance = leg.getJSONObject("distance");
String mTextDistent = distance.getString("text");
System.out.println("distances bitween two point" + mTextDistent);
JSONObject duration = leg.getJSONObject("duration");
String mTextDurestion = duration.getString("text");
mEnd_Address = leg.getString("end_address");
mStart_Address = leg.getString("start_address");
System.out.println("get data from jeson in second arry"
+ mTextDurestion + " " + mEnd_Address + " " + mStart_Address);
JSONArray step = leg.getJSONArray("steps");
mLength = step.length();
mLatitude_End = new double[mLength];
mLongitude_End = new double[mLength];
mLatitude_Start = new double[mLength];
mLongitude_Start = new double[mLength];
for (int k = 0; k < step.length(); k++) {
JSONObject st = step.getJSONObject(k);
System.out.println("enter in third array");
JSONObject end_lo = st.getJSONObject("end_location");
JSONObject start_lo = st
.getJSONObject("start_location");
mLatitude_End[k] = end_lo.getDouble("lat");
mLongitude_End[k] = end_lo.getDouble("lng");
mLatitude_Start[k] = start_lo.getDouble("lat");
mLongitude_Start[k] = start_lo.getDouble("lng");
}
for (int mDistanse = 0; mDistanse < mLength; mDistanse++) {
System.out.println("end location let" + mLatitude_End[mDistanse]);
System.out.println("end location long+"
+ mLongitude_End[mDistanse]);
System.out.println("Start location let"
+ mLatitude_Start[mDistanse]);
System.out.println("Start location long"
+ mLongitude_Start[mDistanse]);
}
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
public class MapOverlay extends com.google.android.maps.Overlay {
public MapOverlay(GeoPoint mGeoPoint) {
}
#Override
public boolean draw(final Canvas canvas, MapView mapView,
boolean shadow, long when) {
Point mpoint = new Point();
Point mpoint1 = new Point();
int let[] = new int[mLength];
int lon[] = new int[mLength];
int let_end[] = new int[mLength];
int lon_end[] = new int[mLength];
GeoPoint newGeoPoint = null;
GeoPoint newGeoPoint1;
for (int k = 0; k < mLength; k++) {
let[k] = (int) (mLatitude_Start[k] * 1E6);
lon[k] = (int) (mLongitude_Start[k] * 1E6);
let_end[k] = (int) (mLatitude_End[k] * 1E6);
lon_end[k] = (int) (mLongitude_End[k] * 1E6);
newGeoPoint1 = new GeoPoint(let_end[k], lon_end[k]);
newGeoPoint = new GeoPoint(let[k], lon[k]);
mapView.getProjection().toPixels(newGeoPoint, mpoint);
mapView.getProjection().toPixels(newGeoPoint1, mpoint1);
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(5);
canvas.drawCircle(mpoint.x, mpoint.y, 5, paint);
paint.setColor(Color.BLUE);
canvas.drawLine(mpoint.x, mpoint.y, mpoint1.x, mpoint1.y, paint);
paint.setColor(Color.BLACK);
paint.setStrokeWidth(100);
paint.setStyle(Paint.Style.FILL);
if(k==mLength-1){
Bitmap bmp = BitmapFactory.decodeResource(activity.getResources(), R.drawable.green_pin);
canvas.drawBitmap(bmp,mpoint1.x ,mpoint1.y-30, null);
}
GeoPoint dumy=new GeoPoint((int)(mIntentLatitude * 1E6), (int)(mIntentLongitude * 1E6));
Point dumy1 = new Point();
mapView.getProjection().toPixels(dumy, dumy1);
Bitmap bmp = BitmapFactory.decodeResource(activity.getResources(), R.drawable.dest_pin);
canvas.drawBitmap(bmp,dumy1.x,dumy1.y - 25, null);
mapView.getController().animateTo(dumy);
mapView.invalidate();
}
return false;
}
}
}
Try this if you want to move map on particular position then get lat or long of that position and just pass in this :
MapController mMapController;
mMapController=mMapView.getController();
mMapController.setCenter(new GeoPoint((int)(lat * 1E6), (int)(lon * 1E6)));
and if you want to draw path between two location then just pass lat and lon in this :
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr="+ String.valueOf(from_lattitude) +","+ String.valueOf(from_longitude) +"&daddr="+ String.valueOf(dest_lati) +","+ String.valueOf(dest_longi)));
startActivity(intent);
Related
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.
I've been trying to work this piece of code for a week now. The route does not come up. My code is below.
I am trying to draw a route between two geopoints - the location which I'm retrieving from a web service.
My log doesn't show any error.
public class TesterGTC extends MapActivity {
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://10.0.2.2:2488/Service1.asmx";
private static final String METHOD_NAME1 = "lastKnownLocationAllValues";
private static final String SOAP_ACTION = NAMESPACE + METHOD_NAME1;
private List<Overlay> mapOverlays;
private Projection projection;
MapView mapView;
double latitude;
double longitude;
double endlat;
double endlong;
GeoPoint geoPoint;
MapController myMC;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // Suppress title bar to give more space
setContentView(R.layout.googletrackingclient);
final String orderID = GoogleTrackingMenu.epcID;
final String vehicleid = GoogleTrackingMenu.vehicleid;
Thread t = new Thread(new Runnable() {
public void run() {
String u = orderID;
String v = vehicleid;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
PropertyInfo propInfo = new PropertyInfo();
propInfo.name = "OID";
propInfo.type = PropertyInfo.STRING_CLASS;
request.addProperty(propInfo, u);
PropertyInfo propInfo2 = new PropertyInfo();
propInfo2.name = "vehicleID";
propInfo2.type = PropertyInfo.STRING_CLASS;
request.addProperty(propInfo2, v);
final TextView textview = (TextView) findViewById(R.id.id1);
final TextView myLoc = (TextView) findViewById(R.id.id2);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
final ArrayList<EPCISGPSResult> resultList = new ArrayList<EPCISGPSResult>();
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
final SoapObject resultRequestSOAP = (SoapObject) envelope
.getResponse();
final int resultInt = resultRequestSOAP.getPropertyCount();
for (int i = 0; i < resultInt; i++) {
SoapObject resultRequest = (SoapObject) resultRequestSOAP
.getProperty(i);
String vehicleID = resultRequest.getProperty("vehicleID").toString();
String driverName = resultRequest.getProperty("driverName").toString();
String latitude = resultRequest.getProperty("latitude").toString();
String longitude = resultRequest.getProperty("longitude").toString();
String startVenue = resultRequest.getProperty("startVenue").toString();
String destination = resultRequest.getProperty("destination").toString();
String dateReceived = resultRequest.getProperty("dateReceived").toString();
String utc = resultRequest.getProperty("utc").toString();
String orderID = resultRequest.getProperty("orderID").toString();
EPCISGPSResult e = new EPCISGPSResult(vehicleID,driverName, latitude, longitude, startVenue,destination, dateReceived, utc, orderID);
resultList.add(e);
}
latitude = Double.parseDouble(resultList.get(0).getLatitude());
longitude = Double.parseDouble(resultList.get(0).getLongitude());
endlat = Double.parseDouble(resultList.get(resultList.size()-1).getLatitude());
endlong = Double.parseDouble(resultList.get(resultList.size()-1).getLongitude());
int beglat = (int)latitude* 1000000;
int endinglat = (int)endlat* 1000000;
int beglong = (int)longitude* 1000000;
int endinglong = (int)endlong* 1000000;
final GeoPoint gP1 = new GeoPoint(beglat, beglong);
final GeoPoint gP2 = new GeoPoint(endinglat, endinglong);
TesterGTC.this.runOnUiThread(new Runnable() {
public void run() {
int pointer = 0;
pointer = 1;
TextView tview = (TextView) findViewById(R.id.id1);
tview.setText("before map");
mapView = (MapView) findViewById(R.id.myGMap);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
myMC = mapView.getController();
myMC.setZoom(15);
int color = Color.RED;
mapOverlays = mapView.getOverlays();
projection = mapView.getProjection();
TextView txxview = (TextView) findViewById(R.id.id2);
txxview.setText("after map");
MyOverlay newO = new MyOverlay(gP1, gP2, color);
/* TextView textview = (TextView) findViewById(R.id.id1);
textview.setText("This is happening");*/
mapOverlays.add(newO);
} });
}
catch (final Exception e) {
TesterGTC.this.runOnUiThread(new Runnable() {
public void run() {
TextView textview = (TextView) findViewById(R.id.id1);
textview.setText("Your error is: " + e.getMessage().toString());
}
});
} finally {
}
}
});
t.start();
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
class MyOverlay extends Overlay{
GeoPoint gp1;
GeoPoint gp2;
int color;
public MyOverlay(GeoPoint gp1, GeoPoint gp2, int color){
this.gp1 = gp1;
this.gp2 = gp2;
this.color = color;
}
public void draw(Canvas canvas, MapView mapView, boolean shadow, GeoPoint gP1 , GeoPoint gP2){
super.draw(canvas, mapView, shadow);
TextView textview = (TextView) findViewById(R.id.id1);
textview.setText("This is ALSO happening");
Paint mPaint = new Paint();
mPaint.setDither(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(2);
Point p1 = new Point();
Point p2 = new Point();
Path path = new Path();
projection.toPixels(gP1, p1);
projection.toPixels(gP2, p2);
path.moveTo(p2.x, p2.y);
path.lineTo(p1.x,p1.y);
canvas.drawPath(path, mPaint);
}
}
}
Here saddr = source & daddr = destination location.
public void showDirections(View view) {
final Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://maps.google.com/maps?" + "saddr="+ latitude + "," + longitude + "&daddr=" + latitude + "," + longitude));
intent.setClassName("com.google.android.apps.maps","com.google.android.maps.MapsActivity");
startActivity(intent);
}
public class HelloItemizedOverlay extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
Context mContext = getApplicationContext();
Bitmap bmp = BitmapFactory.decodeFile("pushpin.png");
Drawable drawable = new BitmapDrawable(bmp);
public HelloItemizedOverlay(Drawable drawable) {
super(boundCenterBottom(drawable));
populate();
}
public HelloItemizedOverlay(Drawable drawable, Context context) {
super(boundCenterBottom(drawable));
mContext = getApplicationContext();
populate();
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
return mOverlays.size();
}
#Override
protected boolean onTap(int index) {
OverlayItem item = mOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(
GoogleTrackingPage.this);
// add the overlay item's title and snippet or create owner
String newMessage = "Your order has the following location details \n\nVehicleID: "
+ vehicle
+ "\nDriver: "
+ driver
+ "\nStart Venue: "
+ starting
+ "\nFinal Destination: "
+ desti
+ "\nLast Updated on:" + dateR;
dialog.setTitle("Order Details for " + orderidfrommenu + " at "
+ locationString);
dialog.setMessage(newMessage);
dialog.show();
return true;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,long when)
{
Paint paint = null;
int x = myList.size();
int lastPoint = x-1;
if(myList.size() <= 2){
latitude = Double.parseDouble(myList.get(0).getLatitude());
longitude = Double.parseDouble(myList.get(0).getLongitude());
}
else{
int lP = myList.size()-2;
latitude = Double.parseDouble(myList.get(lP).getLatitude());
longitude = Double.parseDouble(myList.get(lP).getLongitude());
}
endlat = Double.parseDouble(myList.get(myList.size() - 1).getLatitude());
endlong = Double.parseDouble(myList.get(myList.size() - 1).getLongitude());
int beglat = (int)latitude* 1000000;
int endinglat = (int)endlat* 1000000;
int beglong = (int)longitude* 1000000;
int endinglong = (int)endlong* 1000000;
GeoPoint gP1 = new GeoPoint(beglat, beglong);
GeoPoint gP2 = geoPoint;
gP1=mOverlays.get(0).getPoint();
Projection projection = mapView.getProjection();
if (shadow == false)
{
paint = new Paint();
paint.setAntiAlias(true);
Point point = new Point();
projection.toPixels(gP1, point);
paint.setColor(Color.RED);
Point point2 = new Point();
projection.toPixels(gP2, point2);
paint.setStrokeWidth(5);
canvas.drawLine((float) point.x, (float) point.y, (float) point2.x,
(float) point2.y, paint);
}
return super.draw(canvas, mapView, shadow, when);
}
}
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;
}
I am new to Android. I want to draw a line from one location to another in my application. How can I draw a line between two points in Android? Please help me.
You should add an Overlay to the map and override it's onDraw() method. That way you can draw whatever you want on the map.
use this it works fine for me
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
ArrayList allGeoPoints = getDirections(8.487495, 76.948623,toLat 10.015861, 76.341867toLon);
GeoPoint moveTo = new GeoPoint(startLattitude, startLongigude);
mapController.setCenter(moveTo);
//mc.animateTo(moveTo);
mapController.setZoom(12);
mapView.getOverlays().add(new MyOverlay(allGeoPoints));
public static ArrayList 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 listOfGeopoints = new ArrayList();
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);
Log.e("********************** ",new JsonOperations().convertStreamToString(in).toString());
if (doc != null) {
NodeList nl1, nl2;
nl1 = doc.getElementsByTagName(tag[0]);
nl2 = doc.getElementsByTagName(tag[1]);
if (nl1.getLength() > 0) {
listOfGeopoints = new ArrayList();
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());
listOfGeopoints.add(new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6)));
}
} else {
// No points found
}
}
} catch (Exception e) {
e.printStackTrace();
}
return listOfGeopoints;
}
And myoverlay class
public class MyOverlay extends Overlay {
private ArrayList allGeoPoints;
public MyOverlay(ArrayList allGeoPoints) {
super();
this.allGeoPoints = 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.STROKE);
paint.setStrokeWidth(4);
//paint.setAlpha(100);
if (allGeoPoints != null)
for (int i = 0; i < allGeoPoints.size() - 4; i++) {
GeoPoint gp = (GeoPoint) allGeoPoints.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;
}
}
}
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