Draw line between two points in google map in android [duplicate] - android

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Drawing a line/path on Google Maps
How can i draw line beetween two points in google map?

public class DrivingDirection extends MapActivity implements
IDirectionsListener {
Button btnRedirectHome;
Vector<GeoPoint> mapData = new Vector<GeoPoint>();
Vector<GeoPoint> NearData = new Vector<GeoPoint>();
MapView mapView;
MapController mc;
GeoPoint p;
GeoPoint endpoint;
MapOverlay mapOverlay;
private AlertDialog.Builder alertDialog1, alertDialog;
boolean exception = false;
// ** Called when the activity is first created. *//*
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.courtdetaildetdirection_layout);
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
Bundle extras = getIntent().getExtras();
String courtId = extras != null ? extras.getString("CourtId") : "";
if(GUIStatics.previousActivityNameFalg.equalsIgnoreCase("MatchDetailActivity"))
{
if (GUIStatiMethods
.connectionCheck(DrivingDirection.this)) {
Court_Player_LocationFatcher objectCourt_Player_LocationFatch = new Court_Player_LocationFatcher();
objectCourt_Player_LocationFatch.Court_Player_LocationFatch(GUIStatics.strUserID,courtId);
final CourtDetailFatcher myCourtDetailFatcher = new CourtDetailFatcher();
myCourtDetailFatcher.CourtDetailFatch(courtId);
}
}
else if(GUIStatics.previousActivityNameFalg.equalsIgnoreCase("FavoritesActivity"))
{
if (GUIStatiMethods
.connectionCheck(DrivingDirection.this)) {
Court_Player_LocationFatcher objectCourt_Player_LocationFatch = new Court_Player_LocationFatcher();
objectCourt_Player_LocationFatch.Court_Player_LocationFatch(GUIStatics.strUserID,courtId);
final CourtDetailFatcher myCourtDetailFatcher = new CourtDetailFatcher();
myCourtDetailFatcher.CourtDetailFatch(courtId);
}
}
else
{
if (GUIStatiMethods
.connectionCheck(DrivingDirection.this)) {
Court_Player_LocationFatcher objectCourt_Player_LocationFatch = new Court_Player_LocationFatcher();
objectCourt_Player_LocationFatch.Court_Player_LocationFatch(GUIStatics.strUserID,courtId);
final CourtDetailFatcher myCourtDetailFatcher = new CourtDetailFatcher();
myCourtDetailFatcher.CourtDetailFatch(courtId);
}
}
TextView TextViewCourtDetailHeader = (TextView) this
.findViewById(R.id.TextViewCourtDetailHeader);
TextView TextViewCourtDetailAddress = (TextView) this
.findViewById(R.id.TextViewCourtDetailAddress);
TextView TextViewCourtDetailNoOfCourtAndType = (TextView) this
.findViewById(R.id.TextViewCourtDetailNoOfCourtAndType);
TextView TextViewCourtDetailCourtType = (TextView) this
.findViewById(R.id.TextViewCourtDetailCourtType);
TextView TextViewCourtDetailLight = (TextView) this
.findViewById(R.id.TextViewCourtDetailLight);
TextViewCourtDetailHeader
.setText(CourtDetailDataHandler.object.COURTNAME);
TextViewCourtDetailAddress
.setText(CourtDetailDataHandler.object.COURTADDRESS);
TextViewCourtDetailNoOfCourtAndType
.setText(CourtDetailDataHandler.object.NUMBEROFCOURT);
TextViewCourtDetailCourtType
.setText(CourtDetailDataHandler.object.COURTTYPE);
TextViewCourtDetailLight.setText("Lights: "
+ CourtDetailDataHandler.object.COURTLIGHT);
String url = "http://maps.google.com/maps?f=d&hl=en&saddr="
+ Court_Player_LocationHandler.mCOURTLAT + ","
+ Court_Player_LocationHandler.mCOURTLON + "&daddr="
+ Court_Player_LocationHandler.mUSERLAT + ","
+ Court_Player_LocationHandler.mUSERLON
+ "&ie=UTF8&0&om=0&z=20&output=kml";
Document d = GetDataFromServer(url);
if (exception) {
exception = false;
GeoPoint source = new GeoPoint(
(int) (Double
.parseDouble(Court_Player_LocationHandler.mCOURTLAT) * 1E6),
(int) (Double
.parseDouble(Court_Player_LocationHandler.mCOURTLON) * 1E6));
mapData.add(source);
GeoPoint destination = new GeoPoint(
(int) (Double
.parseDouble(Court_Player_LocationHandler.mUSERLAT) * 1E6),
(int) (Double
.parseDouble(Court_Player_LocationHandler.mUSERLON) * 1E6));
mapData.add(destination);
} else {
ParseServerData(d);
}
LinearLayout zoomLayout = (LinearLayout) findViewById(R.id.zoom);
View zoomView = mapView.getZoomControls();
zoomLayout.addView(zoomView, new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mapView.displayZoomControls(true);
mc = mapView.getController();
for (int i = 0; i < mapData.size(); i++) {
GeoPoint gp = mapData.get(i);
mc.animateTo(gp);
}
for (int i = 0; i < NearData.size(); i++) {
GeoPoint gp = mapData.get(i);
mc.animateTo(gp);
}
mc.setZoom(18);
// ---Add a location marker---
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
class MapOverlay extends com.google.android.maps.Overlay {
Paint innerPaint;
int infoWindowOffsetX, infoWindowOffsetY, testX, testY, id;
boolean showWindow = false;
Bitmap bitmap, bmp, bitMoreInformation;
String argName;
boolean temp = true;
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.marker);
// ---translate the GeoPoint to screen pixels---
Paint myPaintBlack1 = new Paint();
myPaintBlack1.setColor(Color.BLUE);
myPaintBlack1.setStyle(Style.STROKE);
myPaintBlack1.setStrokeWidth(4f);
Point screenPts[] = new Point[mapData.size()];
for (int i = 0; i < mapData.size(); i++) {
Point screenPt = new Point();
GeoPoint gp = mapData.get(i);
mapView.getProjection().toPixels(gp, screenPt);// screenPts[i]);
screenPts[i] = screenPt;
if (i == 0)
canvas.drawBitmap(bmp, screenPts[i].x - bmp.getWidth() / 2,
screenPts[i].y - bmp.getHeight(), null);
if (i == mapData.size() - 1)
canvas.drawBitmap(bmp, screenPts[i].x - bmp.getWidth() / 2,
screenPts[i].y - bmp.getHeight(), null);
}
for (int i = 0; i < NearData.size(); i++) {
Point screenPs = new Point();
GeoPoint gp = mapData.get(i);
mapView.getProjection().toPixels(gp, screenPs);// screenPts[i]);
canvas.drawBitmap(bmp, screenPs.x - bmp.getWidth() / 2,
screenPs.y - bmp.getHeight(), null);
}
for (int i = 1; i < screenPts.length; i++) {
canvas.drawLine(screenPts[i - 1].x, screenPts[i - 1].y,
screenPts[i].x, screenPts[i].y, myPaintBlack1);
}
return true;
}
public Paint getInnerPaint() {
if (innerPaint == null) {
innerPaint = new Paint();
innerPaint.setARGB(225, 75, 75, 75); // gray
innerPaint.setAntiAlias(true);
}
return innerPaint;
}
#Override
public boolean onTap(GeoPoint p, MapView mapView) {
return true;
}
}
public Document GetDataFromServer(String url) {
try {
URL updateURL = new URL(url);
URLConnection conn = updateURL.openConnection();
InputStream is = conn.getInputStream();
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(is);
is.close();
return document;
} catch (Exception e) {
exception = true;
System.out.print("Exception:-" + e);
}
exception = true;
return null;
}
private void ParseServerData(Document doc) {
Element rootElement = doc.getDocumentElement();
rootElement.normalize();
NodeList nodeLst = doc.getElementsByTagName("LookAt");
int c = nodeLst.getLength();
System.out.println("count= " + c);
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
// Points p = new Points();
Element Elmnt = (Element) fstNode;
double lat = Double
.parseDouble(getTextValue(Elmnt, "latitude"));
double lng = Double
.parseDouble(getTextValue(Elmnt, "longitude"));
GeoPoint gp = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mapData.add(gp);
}
}
}
public String getTextValue(Element ele, String tagName) {
String textVal = "";
NodeList nl = ele.getElementsByTagName(tagName);
if (nl != null && nl.getLength() > 0) {
Element el = (Element) nl.item(0);
NodeList ndlist = el.getChildNodes();
Node node = ndlist.item(0);
if (node != null)
textVal = node.getNodeValue();
}
return textVal;
}
// handler for the background updating
Handler progressHandler = new Handler() {
public void handleMessage(Message msg) {
}
};
#Override
protected boolean isRouteDisplayed() {
return false;
}
public void onDirectionsAvailable(Route route,
com.cipl.Courts.DrivingDirections.Mode mode) {
}
public void onDirectionsNotAvailable() {
}
}
The above code draw line between two point on Map in android.

Related

moving map in mapview from one location to another in android

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);

Overlays not showing up on MapView

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

Draw Route on Android Map not working...?

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);
}
}

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

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

How can I draw a line between two points in Google map in Android?

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;
}
}
}

Categories

Resources