Class inside of for loop - android

newbie, I have class:
class PolyOverlay extends Overlay {
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow)
{
try {
List<GeoPoint> points = new ArrayList<GeoPoint>();
GeoPoint tmpPoint;
double lat2;
double lng2;
String args[] = {"",""};
args = sitesList.getpolyLine().get(daI).split("\\;");
//Toast.makeText(getApplicationContext(),"T: " + args[0],Toast.LENGTH_SHORT ).show();
for (int i = 0; i < args.length; i++) {
String coordinates2[] = {"",""};
String args2[] = {"",""};
args2 = args[i].split("\\,");
coordinates2[0]= args2[0];
coordinates2[1]= args2[1];
//Toast.makeText(getApplicationContext(),"T: " + coordinates2[0],Toast.LENGTH_SHORT ).show();
lat2= Double.parseDouble(coordinates2[0]);
lng2= Double.parseDouble(coordinates2[1]);
tmpPoint = new GeoPoint((int) (lat2 * 1E6), (int) (lng2 * 1E6) );
points.add(tmpPoint);
}
//for(Polygon polygonTemp : polygonList)
//{
Path p = new Path();
Projection projection = mapView.getProjection();
boolean firstTime = true;
for(GeoPoint geoPoint : points)
{
Point drawPoint = new Point();
projection.toPixels(geoPoint, drawPoint);
if(firstTime)
{
p.moveTo(drawPoint.x, drawPoint.y);
firstTime = false;
}
else
{
p.lineTo(drawPoint.x, drawPoint.y);
}
}
p.setFillType(Path.FillType.EVEN_ODD);
Paint polyPaint = new Paint();
polyPaint.setStrokeWidth(1);
polyPaint.setStyle(Paint.Style.FILL_AND_STROKE);
polyPaint.setAntiAlias(true);
polyPaint.setColor(Color.BLUE);
polyPaint.setAlpha(30);
canvas.drawPath(p, polyPaint);
firstTime = true;
//}
super.draw(canvas, mapView, shadow);
} catch (Exception e) {
Toast.makeText(epapp.this, "Err: " + e, Toast.LENGTH_LONG).show();
}
}
}
Then inside an xml loop I do this:
for (int i = 0; i < sitesList.getStrap().size(); i++) {
//icons
String pargs[] = sitesList.getCentr().get(i).split("\\,");
String coordinates3[] = {"",""};
coordinates3[0] = pargs[0].toString();
coordinates3[1] = pargs[1].toString();
//Toast.makeText(epapp.this, "Center: " + coordinates3[0], Toast.LENGTH_LONG).show();
double lat2 = Double.parseDouble(coordinates3[0]);
double lng2 = Double.parseDouble(coordinates3[1]);
np = new GeoPoint(
(int) (lat2 * 1E6),
(int) (lng2 * 1E6));
Drawable drawable = this.getResources().getDrawable(R.drawable.iconresidential);
IconItemizedOverlay itemizedoverlay = new IconItemizedOverlay(drawable,this);
OverlayItem overlayitem = new OverlayItem(np, "Property Information", "JONES EMERSON ROBERT JR & SARA MARIA<br>1032 Briarwood Dr Wauchula 33873<br>HARDEE County<br>STRAP 05-34-25-0865-00001-0020");
itemizedoverlay.addOverlay(overlayitem);
mapView.getOverlays().add(itemizedoverlay);
//if (i==1){
//polyString = sitesList.getpolyLine().get(i);
daI=i;
//polygon
PolyOverlay myPolyOverlay = new PolyOverlay();
mapView.getOverlays().add(myPolyOverlay);
//}
}
ok so the "problem" is if I do the //if (i==1){ part in the loop where "daI" is being set to "i", my "Polygon" is displayed on the map for that item in the XML, if I "REM" it out, the Polygon(s) overlay are always the last item in the XML. The xml list has 20 items in the list always and it seems as if the the "daI" variable is always 19 (last index in the list 0-19)
Obviously not do something so the PolyOverlay class gets "finished" before the xml loop is done?? It like the xml loop flys through sets "daI" to the last one and the PolyOverlay is loading the polygon for that last item...
My icons are just fine btw on the map...

k, I'm retarded: I had to do this:
int di = 0;
PolyOverlay(int n) {
di = n;
}
in my PolyOvelay class then pass the "i" from the xml for loop to it...
PolyOverlay myPolyOverlay = new PolyOverlay(i);
mapView.getOverlays().add(myPolyOverlay);

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

Can anyone guide me how to get Google Directions between two locations using JSON

I have heard that KML file is no longer available since 27 July 2012 (because Google has changed the structure of retrieving Google Directions, now you can only get it by JSON or XML)
So plz guide me how to make road route between 2 location.
BELOW CODE IS WORKING FINE NW ENJOY GUYS
This is my code:
I refered this link : http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/
PlacesMapActivity.java
In below code it is showing straight line between 2 point.
public class PlacesMapActivity extends MapActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_places);
Intent i = getIntent(); // Getting intent data
String user_latitude = i.getStringExtra("user_latitude");// Users current geo location
String user_longitude = i.getStringExtra("user_longitude");//Userscurrent geo location
nearPlaces = (PlacesList) i.getSerializableExtra("near_places");// Nearplaces list
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
geoPoint = new GeoPoint((int) (Double.parseDouble(user_latitude) * 1E6), (int) (Double.parseDouble(user_longitude) * 1E6));// Geopoint to place on map
geoPoint1 = new GeoPoint((int) (Double.parseDouble("12.930621") * 1E6),
(int) (Double.parseDouble("77.581710") * 1E6));//Geopoint to Clientplace on map
Drawable drawable_user = this.getResources()
.getDrawable(R.drawable.mark_red); // Drawable marker icon
Drawable drawable_client = this.getResources()
.getDrawable(R.drawable.mark_blue); // Drawable Client icon
Drawable drawable = this.getResources()
.getDrawable(R.drawable.clientflag); // Drawable marker icon
// Map overlay item
itemizedOverlay = new AddItemizedOverlay(drawable_user, this);
overlayitem = new OverlayItem(geoPoint, "Your Location","That is you!");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
itemizedOverlay.populateNow();
// Map client overlay item
itemizedOverlay1 = new AddItemizedOverlay(drawable_client, this);
overlayitem1 = new OverlayItem(geoPoint1, "Your Location2", "I am ur client!");
itemizedOverlay1.addOverlay(overlayitem1);
mapOverlays.add(itemizedOverlay1);
itemizedOverlay1.populateNow();
// Map client overlay item
itemizedOverlay = new AddItemizedOverlay(drawable, this);
mc = mapView.getController();
// These values are used to get map boundary area
// The area where you can see all the markers on screen
int minLat = Integer.MAX_VALUE;
int minLong = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int maxLong = Integer.MIN_VALUE;
// check for null in case it is null
if (nearPlaces.results != null) {
// loop through all the places
for (Place place : nearPlaces.results) {
latitude = place.geometry.location.lat; // latitude
longitude = place.geometry.location.lng; // longitude
// Geopoint to place on map
geoPoin = new GeoPoint((int) (latitude * 1E6),
(int) (longitude * 1E6));
// Map overlay item
overlayitem = new OverlayItem(geoPoin, place.name,
place.vicinity);
itemizedOverlay.addOverlay(overlayitem);
// calculating map boundary area
minLat = (int) Math.min( geoPoin.getLatitudeE6(), minLat );
minLong = (int) Math.min( geoPoin.getLongitudeE6(), minLong);
maxLat = (int) Math.max( geoPoin.getLatitudeE6(), maxLat );
maxLong = (int) Math.max( geoPoin.getLongitudeE6(), maxLong );
}
mapOverlays.add(itemizedOverlay);
// showing all overlay items
itemizedOverlay.populateNow();
}
// Adjusting the zoom level so that you can see all the markers on map
mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
// Showing the center of the map
mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
mc.animateTo(geoPoint1);
//mapView.postInvalidate();
myoverlay = new MyOverlay();
mapOverlays.add(myoverlay);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.activity_main, menu);
return true;
}
/**
* Event Handling for Individual menu item selected
* Identify single menu item by it's id
* */
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.mylocation:
// Single menu item is selected do something
Toast.makeText(PlacesMapActivity.this, "Moving To Current location", Toast.LENGTH_SHORT).show();
// geoPoint.gpsCurrentLocation();
return true;
case R.id.mapStreet:
Toast.makeText(PlacesMapActivity.this, "Map Normal Street View", Toast.LENGTH_SHORT).show();
if(mapView.isSatellite()==true){
mapView.setSatellite(false);
}
return true;
case R.id.mapSatellite:
Toast.makeText(PlacesMapActivity.this, "Map Satellite View", Toast.LENGTH_SHORT).show();
if(mapView.isSatellite()==false){
mapView.setSatellite(true);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
add this road route
private void DrawPath(GeoPoint scrgeoPoint, GeoPoint destgeoPoint, GeoPoint destgeopointsearch, int green, MapView mMapView) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(makeUrl(scrgeoPoint, destgeoPoint, destgeopointsearch));
HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = null;
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
reader.close();
String result = sb.toString();
JSONObject jsonObject = new JSONObject(result);
JSONArray routeArray = jsonObject.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<GeoPoint> pointToDraw = decodePoly(encodedString);
mMapView.getOverlays().add(new MyOverLay(pointToDraw));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private List<GeoPoint> decodePoly(String encoded) {
List<GeoPoint> poly = new ArrayList<GeoPoint>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
GeoPoint p = new GeoPoint((int) (((double) lat / 1E5) * 1E6),
(int) (((double) lng / 1E5) * 1E6));
poly.add(p);
}
return poly;
}
private String makeUrl(GeoPoint scrgeoPoint, GeoPoint destgeoPoint, GeoPoint destgeopointsearch) {
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append(Double.toString((double) scrgeoPoint.getLatitudeE6() / 1.0E6));
urlString.append(",");
urlString.append(Double.toString((double) scrgeoPoint.getLongitudeE6() / 1.0E6));
urlString.append("&destination=");// to
urlString.append(Double.toString((double) destgeoPoint.getLatitudeE6() / 1.0E6));
urlString.append(",");
urlString.append(Double.toString((double) destgeoPoint.getLongitudeE6() / 1.0E6));
/* urlString.append("&destination=");// searchto
urlString.append(Double.toString((double) destgeopointsearch.getLatitudeE6() / 1.0E6));
urlString.append(",");
urlString.append(Double.toString((double) destgeopointsearch.getLongitudeE6() / 1.0E6));
*/
urlString.append("&sensor=false");
Log.d("xxx", "URL=" + urlString.toString());
return urlString.toString();
}
At Last i got road route map between two point.. Add this code.
class MyOverLay extends Overlay {
private int pathColor;
private final List<GeoPoint> points;
private boolean drawStartEnd;
public MyOverLay(List<GeoPoint> pointToDraw) {
this(pointToDraw, Color.MAGENTA, true);
}
public MyOverLay(List<GeoPoint> points, int pathColor, boolean drawStartEnd) {
this.points = points;
this.pathColor = pathColor;
this.drawStartEnd = drawStartEnd;
}
private void drawOval(Canvas canvas, Paint paint, Point point) {
Paint ovalPaint = new Paint(paint);
ovalPaint.setStyle(Paint.Style.FILL_AND_STROKE);
ovalPaint.setStrokeWidth(2);
ovalPaint.setColor(Color.BLUE);
int _radius = 6;
RectF oval = new RectF(point.x - _radius, point.y - _radius,
point.x + _radius, point.y + _radius);
canvas.drawOval(oval, ovalPaint);
}
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
Projection projection = mapView.getProjection();
if (shadow == false && points != null) {
Point startPoint = null, endPoint = null;
Path path = new Path();
// We are creating the path
for (int i = 0; i < points.size(); i++) {
GeoPoint gPointA = points.get(i);
Point pointA = new Point();
projection.toPixels(gPointA, pointA);
if (i == 0) { // This is the start point
startPoint = pointA;
path.moveTo(pointA.x, pointA.y);
} else {
if (i == points.size() - 1)// This is the end point
endPoint = pointA;
path.lineTo(pointA.x, pointA.y);
}
}
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(pathColor);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
paint.setAlpha(90);
if (getDrawStartEnd()) {
if (startPoint != null) {
drawOval(canvas, paint, startPoint);
}
if (endPoint != null) {
drawOval(canvas, paint, endPoint);
}
}
if (!path.isEmpty())
canvas.drawPath(path, paint);
}
return super.draw(canvas, mapView, shadow, when);
}
public boolean getDrawStartEnd() {
return drawStartEnd;
}
public void setDrawStartEnd(boolean markStartEnd) {
drawStartEnd = markStartEnd;
}
}
}
You can see my post here with full answer on how to do it in JSON since Google shut down KML.

MapView panning and zooming is slow after adding many Overlays

So I've spent a good amount of time attempting to figure out how to speed this up, but I'm out of ideas now. I have a class, mapPopup in which a MapView is displayed over the entire screen. There is an array of an array of GeoPoint in mapPopup, and I want to draw lines between each GeoPoint in the 2nd dimensions of the array. I've accomplished this task already using a custom class, mapOverlay, that extends Overlay, but the problem I am having is that once all the map overlays are drawn, the map is extremely slow to zoom or pan. Once all the overlays are added to the map there are often over 2000, but they are all very small.
Thinking that the map would work more quickly if there were less overlays, I drew all the lines to three seperate overlays instead of a seperate overlay for each line. This actually resulted in SLOWER panning and zooming of the map, so I reverted back to the many small overlays.
I would appreciate some informative and easy to understand descriptions of a method that I could employ to make the map faster. Pseudocode or real code for the potential method would also help me to understand it better. My code is posted below. Once more, please note that my overlays and map display properly; I would just like a method that will allow faster panning and zooming.
mapOverlay class
public class mapOverlay extends Overlay {
private Projection projection;
private GeoPoint gp1;
private GeoPoint gp2;
private int color;
public mapOverlay(int color, MapView map, GeoPoint geo1, GeoPoint geo2) {
// super();
this.projection = map.getProjection();
this.gp1 = geo1;
this.gp2 = geo2;
this.color = color;
}
public void draw(Canvas canvas, MapView mapv, boolean shadow) {
super.draw(canvas, mapv, false);
Paint mPaint = new Paint();
mPaint.setDither(true);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(4);
mPaint.setColor(this.color);
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);
}
}
mapPopup class
public class mapPopup extends MapActivity {
public String[] trailNames;
public String tableName = "";
public int numTrails = 0;
public static GeoPoint[][] geoPoints;
public int[] colors = new int[] { Color.WHITE, Color.BLUE, Color.CYAN,
Color.RED, Color.YELLOW, Color.MAGENTA, Color.GRAY, Color.LTGRAY };
public int[] newColors;
// public Bitmap b;
public GeoPoint firstP;
public void loadMapData(Bitmap b, MapView map, int[] colors,
GeoPoint[][] GPAA, int ZoomLevel) {
// GPAA holds an array of an array of GeoPoint
Log.i("DEBUG", "starting loadMapDataTask");
map.setSatellite(true);
MapController mc = map.getController();
mapOverlay[][] mapOverlay = new mapOverlay[GPAA.length][];
Log.i("DEBUG", "length of GPAA is: " + GPAA.length);
// i cycles through the first dimension of GPAA
for (int i = 0; i < GPAA.length; i++) {
GeoPoint[] geoPoints = GPAA[i];
int length = geoPoints.length - 1;
mapOverlay[i] = new mapOverlay[length]; //
int pointCount = 0;
// z cycles through the second dimension of GPAA
for (int z = 0; z < length; z++) {
mapOverlay[i][z] = new mapOverlay(colors[i], map,
geoPoints[pointCount], geoPoints[pointCount + 1]);
pointCount++;
}
}
// Actually adds overlays to map
List<Overlay> mapOverlays = map.getOverlays();
for (int i = 0; i < mapOverlay.length; i++) {
int length = mapOverlay[i].length;
Log.i("DEBUG", "Adding map overlays for trail: " + i);
Log.i("DEBUG", "Length of mapOverlay[i] is: " + length);
for (int z = 0; z < length; z++) {
mapOverlays.add(mapOverlay[i][z]);
}
}
mc.animateTo(GPAA[0][0]);
mc.setZoom(ZoomLevel);
Rect r = new Rect();
map.getDrawingRect(r);
map.invalidate(r);
}
public static class runBGLoad extends
AsyncTask<bgLoadParam, Integer, GeoPoint[][]> {
public GeoPoint[][] geoPoints;
protected GeoPoint[] getGPa(Context context, String name, int ID) {
File file = context.getFileStreamPath(name);
if (file.exists() == false) {
Log.i("DEBUG", "Creating file");
InputStream is;
FileOutputStream fos;
try {
Log.i("DEBUG", "id is " + ID);
is = context.getResources().openRawResource(ID);
byte[] buffer = new byte[is.available()];
is.read(buffer);
fos = context.openFileOutput(name, Context.MODE_PRIVATE);
fos.write(buffer);
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.i("DEBUG", "File already exists");
}
// Log.i("DEBUG", "starting to get geopoints");
List<Location> gpsPoints = XMLParser.getPoints(file);
int i = 0;
int index = 0;
GeoPoint[] geoPoints = new GeoPoint[gpsPoints.size()];
// makes list of gpsPoints into GeoPoint[]
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();
i++;
}
return geoPoints;
}
#Override
protected GeoPoint[][] doInBackground(bgLoadParam... params) {
Context context = params[0].getContext();
int tNLength = params[0].getTNames().length;
geoPoints = new GeoPoint[tNLength][];
for (int i = 0; i < params[0].getTNames().length; i++) {
String modName = params[0].getTNames()[i].toLowerCase()
.replace(' ', '_');
int identifier = context.getResources().getIdentifier(modName,
"raw", context.getPackageName());
geoPoints[i] = getGPa(params[0].getContext(), modName
+ "_mapfile", identifier);
}
Log.i("DEBUG", "TEST");
mapPopup.geoPoints = geoPoints;
Log.i("DEBUG", "TEST2");
return geoPoints;
}
#Override
protected void onPostExecute(GeoPoint[][] result) {
Log.i("DEBUG", "The points are loaded.");
mapPopup.geoPoints = result;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String[] extras = intent.getStringArrayExtra("strings");
tableName = extras[1];
numTrails = Integer.parseInt(extras[2]);
trailNames = intent.getStringArrayExtra("trailNamesA");
super.onCreate(savedInstanceState);
setContentView(R.layout.map_popup_layout);
newColors = new int[numTrails];
for (int i = 0; i < numTrails; i++) {
newColors[i] = colors[i];
}
ViewGroup layout = (ViewGroup) findViewById(R.id.map_popup);
TextView[] tVs = new TextView[numTrails];
for (int i = 0; i < numTrails; i++) {
LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tVs[i] = new TextView(getApplicationContext());
tVs[i].setText(trailNames[i]);
tVs[i].setId(i + 700);
tVs[i].setTextColor(colors[i]);
tVs[i].setBackgroundColor(Color.BLACK);
if (i > 0) {
params.addRule(RelativeLayout.BELOW, (699 + i));
}
layout.addView(tVs[i], params);
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
MapView map = (MapView) findViewById(R.id.popupMV);
Bitmap b = Bitmap.createBitmap(map.getWidth(), map.getHeight(),
Bitmap.Config.RGB_565);
try {
trailsActivity.mapPreLoad.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
loadMapData(b, map, newColors, geoPoints, 17);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
I'm currently facing the same problematic, and I just found a workaround : prevent the overlays from drawing when zooming or panning. That's not perfect and I'm still looking for a better solution, but at least the map is usable without waiting 5 seconds for each pan or zoom.
Here is the code I used in my Overlay extension. It's not Java but C# (using Monodroid) - but it should be easily understandable.
public override bool OnTouchEvent (MotionEvent e, Android.GoogleMaps.MapView mapView)
{
if (e.Action == MotionEventActions.Down)
_mustDraw = false;
else if (e.Action == MotionEventActions.Up)
_mustDraw = true;
return base.OnTouchEvent (e, mapView);
}
public override void Draw (Android.Graphics.Canvas canvas, Android.GoogleMaps.MapView mapView, bool shadow)
{
if (shadow || !_mustDraw)
return;
// ...
}
That solution works for every map-touch based action, and now performs with a good speed, I just lack implementation of the same behaviour when zooming in or out using built-in zoom controls, but I first need to fight some of my bugs before doing this part, I'll come back on this part later.

path tracing program in android

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

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

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.

Categories

Resources