1

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;
}
}
}
Rao's
  • 1,087
  • 8
  • 24
  • 45

1 Answers1

0

You can see my post here with full answer on how to do it in JSON since Google shut down KML.

Community
  • 1
  • 1
Hesham Saeed
  • 5,358
  • 7
  • 37
  • 57
  • hi can anyone say me how to refresh my map using menu Refresh button. Wn i press Refresh menu button map must get refresh... thanks in advance – Rao's Aug 22 '12 at 11:57
  • 1
    hi, i am looking for road route between current location and searched location...above is my code quick reference see this line(add this road route private void DrawPath(GeoPoint scrgeoPoint, GeoPoint destgeoPoint, GeoPoint destgeopointsearch, int green, MapView mMapView) { )Can any one help me.. destgeopointsearch is my serch location and scrgeoPoint is my current loaction... thank u in advance. – Rao's Aug 28 '12 at 10:49
  • Plz look over this link http://stackoverflow.com/questions/12351670/quick-dialog-using-onclick-search-view-in-android#comment16586215_12351670 – Rao's Sep 11 '12 at 04:55