Displaying multiple routes using Directions API in Android - android

I am using this class to display a route on a map. The problem is that it only displays one route. What I want to do is display multiple alternate routes on the map. Even thought the server response has multiple routes, it only parses the first route and displays it. What changes should I make to display all the routes that the google server returns.Here is my class.
public class GMapV2Direction {
public final static String MODE_DRIVING = "driving";
public final static String MODE = "walking";
public final static String MODE_WALKING = "walking";
public GMapV2Direction() { }
public Document getDocument(LatLng start, LatLng end, String mode) {
String url = "http://maps.googleapis.com/maps/api/directions/xml?"
+ "origin=" + start.latitude + "," + start.longitude
+ "&destination=" + end.latitude + "," + end.longitude
+ "&sensor=false&units=metric&mode="+MODE+"alternatives=true";
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost, localContext);
InputStream in = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String getDurationText (Document doc) {
NodeList nl1 = doc.getElementsByTagName("duration");
Node node1 = nl1.item(0);
NodeList nl2 = node1.getChildNodes();
Node node2 = nl2.item(getNodeIndex(nl2, "text"));
Log.i("DurationText", node2.getTextContent());
return node2.getTextContent();
}
public int getDurationValue (Document doc) {
NodeList nl1 = doc.getElementsByTagName("duration");
Node node1 = nl1.item(0);
NodeList nl2 = node1.getChildNodes();
Node node2 = nl2.item(getNodeIndex(nl2, "value"));
Log.i("DurationValue", node2.getTextContent());
return Integer.parseInt(node2.getTextContent());
}
public String getDistanceText (Document doc) {
NodeList nl1 = doc.getElementsByTagName("distance");
Node node1 = nl1.item(0);
NodeList nl2 = node1.getChildNodes();
Node node2 = nl2.item(getNodeIndex(nl2, "text"));
Log.i("DistanceText", node2.getTextContent());
return node2.getTextContent();
}
public int getDistanceValue (Document doc) {
NodeList nl1 = doc.getElementsByTagName("distance");
Node node1 = nl1.item(0);
NodeList nl2 = node1.getChildNodes();
Node node2 = nl2.item(getNodeIndex(nl2, "value"));
Log.i("DistanceValue", node2.getTextContent());
return Integer.parseInt(node2.getTextContent());
}
public String getStartAddress (Document doc) {
NodeList nl1 = doc.getElementsByTagName("start_address");
Node node1 = nl1.item(0);
Log.i("StartAddress", node1.getTextContent());
return node1.getTextContent();
}
public String getEndAddress (Document doc) {
NodeList nl1 = doc.getElementsByTagName("end_address");
Node node1 = nl1.item(0);
Log.i("EndAddress", node1.getTextContent());
return node1.getTextContent();
}
public String getCopyRights (Document doc) {
NodeList nl1 = doc.getElementsByTagName("copyrights");
Node node1 = nl1.item(0);
Log.i("CopyRights", node1.getTextContent());
return node1.getTextContent();
}
public ArrayList<LatLng> getDirection (Document doc) {
NodeList nl1, nl2, nl3;
ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
nl1 = doc.getElementsByTagName("step");
if (nl1.getLength() > 0) {
for (int i = 0; i < nl1.getLength(); i++) {
Node node1 = nl1.item(i);
nl2 = node1.getChildNodes();
Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
nl3 = locationNode.getChildNodes();
Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
double lat = Double.parseDouble(latNode.getTextContent());
Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
double lng = Double.parseDouble(lngNode.getTextContent());
listGeopoints.add(new LatLng(lat, lng));
locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
nl3 = locationNode.getChildNodes();
latNode = nl3.item(getNodeIndex(nl3, "points"));
ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
for(int j = 0 ; j < arr.size() ; j++) {
listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude));
}
locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
nl3 = locationNode.getChildNodes();
latNode = nl3.item(getNodeIndex(nl3, "lat"));
lat = Double.parseDouble(latNode.getTextContent());
lngNode = nl3.item(getNodeIndex(nl3, "lng"));
lng = Double.parseDouble(lngNode.getTextContent());
listGeopoints.add(new LatLng(lat, lng));
}
}
return listGeopoints;
}
private int getNodeIndex(NodeList nl, String nodename) {
for(int i = 0 ; i < nl.getLength() ; i++) {
if(nl.item(i).getNodeName().equals(nodename))
return i;
}
return -1;
}
private ArrayList<LatLng> decodePoly(String encoded) {
ArrayList<LatLng> poly = new ArrayList<LatLng>();
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;
LatLng position = new LatLng((double) lat / 1E5, (double) lng / 1E5);
poly.add(position);
}
return poly;
}
}

i think you don't have to get the response of Google Server and parse it in Document, other wise you can convert from InputStream to String using:
private String convertStreamToString(final InputStream input) throws Exception {
try {
final BufferedReader reader = new BufferedReader(new InputStreamReader(input));
final StringBuffer sBuf = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
sBuf.append(line);
}
return sBuf.toString();
} catch (Exception e) {
throw e;
} finally {
try {
input.close();
} catch (Exception e) {
throw e;
}
}
then you will have to parse the response as JSONObject
JSONObject jSONObject = new JSONObject(string);
then you get JSONArray named routes
JSONArray routeJSONArray = jSONObject.getJSONArray("routes");
now you can start fetching data from each route by getting its index from JSONArray.
i have written a snippet of code as a model of route
Route.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import com.google.android.gms.maps.model.Polyline;
public class Route implements Serializable {
private static final long serialVersionUID = 1L;
private Bound bounds;
private String copyrights;
private List<Leg> legs;
private Polyline overviewPolyLine;
private String summary;
public Route(Context context) {
legs = new ArrayList<Leg>();
}
public Bound getBounds() {
return bounds;
}
public void setBounds(Bound bounds) {
this.bounds = bounds;
}
public String getCopyrights() {
return copyrights;
}
public void setCopyrights(String copyrights) {
this.copyrights = copyrights;
}
public List<Leg> getLegs() {
return legs;
}
public void setLegs(List<Leg> legs) {
this.legs = legs;
}
public void addLeg(Leg leg) {
this.legs.add(leg);
}
public Polyline getOverviewPolyLine() {
return overviewPolyLine;
}
public void setOverviewPolyLine(Polyline overviewPolyLine) {
this.overviewPolyLine = overviewPolyLine;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
Bound.java
import com.google.android.gms.maps.model.LatLng;
public class Bound {
private LatLng northEast;
private LatLng southWest;
public LatLng getNorthEast() {
return northEast;
}
public void setNorthEast(LatLng northEast) {
this.northEast = northEast;
}
public LatLng getSouthWest() {
return southWest;
}
public void setSouthWest(LatLng southWest) {
this.southWest = southWest;
}
}
Leg.java
import java.util.ArrayList;
import java.util.List;
import com.google.android.gms.maps.model.LatLng;
public class Leg {
private Distance distance;
private Duration duration;
private String endAddress;
private LatLng endLocation;
private String startAddress;
private LatLng startLocation;
private List<Step> steps;
public Leg() {
steps = new ArrayList<Step>();
}
public Distance getDistance() {
return distance;
}
public void setDistance(Distance distance) {
this.distance = distance;
}
public Duration getDuration() {
return duration;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
public String getEndAddress() {
return endAddress;
}
public void setEndAddress(String endAddress) {
this.endAddress = endAddress;
}
public LatLng getEndLocation() {
return endLocation;
}
public void setEndLocation(LatLng endLocation) {
this.endLocation = endLocation;
}
public String getStartAddress() {
return startAddress;
}
public void setStartAddress(String startAddress) {
this.startAddress = startAddress;
}
public LatLng getStartLocation() {
return startLocation;
}
public void setStartLocation(LatLng startLocation) {
this.startLocation = startLocation;
}
public List<Step> getSteps() {
return steps;
}
public void setSteps(List<Step> steps) {
this.steps = steps;
}
public void addStep(Step step) {
this.steps.add(step);
}
}
Distance.java
public class Distance {
private String text;
private long value;
public Distance(String text, long value) {
this.text = text;
this.value = value;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public long getValue() {
return value;
}
public void setValue(long value) {
this.value = value;
}
}
Duration.java
public class Duration {
public Duration(String text, long value) {
this.text = text;
this.value = value;
}
private String text;
private long value;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public long getValue() {
return value;
}
public void setValue(long value) {
this.value = value;
}
}
Step.java
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import com.google.android.gms.maps.model.LatLng;
import com.nweave.etaxi.driver.R;
public class Step {
private Distance distance;
private Duration duration;
private LatLng endLocation;
private LatLng startLocation;
private String htmlInstructions;
private String travelMode;
private List<LatLng> points;
public List<LatLng> getPoints() {
return points;
}
public void setPoints(List<LatLng> points) {
this.points = points;
}
public Distance getDistance() {
return distance;
}
public void setDistance(Distance distance) {
this.distance = distance;
}
public Duration getDuration() {
return duration;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
public LatLng getEndLocation() {
return endLocation;
}
public void setEndLocation(LatLng endLocation) {
this.endLocation = endLocation;
}
public LatLng getStartLocation() {
return startLocation;
}
public void setStartLocation(LatLng startLocation) {
this.startLocation = startLocation;
}
public String getHtmlInstructions() {
return htmlInstructions;
}
public void setHtmlInstructions(String htmlInstructions) {
this.htmlInstructions = htmlInstructions;
}
public String getTravelMode() {
return travelMode;
}
public void setTravelMode(String travelMode) {
this.travelMode = travelMode;
}
}
the parsing function will be
public List<Route> parse(String routesJSONString) throws Exception {
try {
List<Route> routeList = new ArrayList<Route>();
final JSONObject jSONObject = new JSONObject(routesJSONString);
JSONArray routeJSONArray = jSONObject.getJSONArray(ROUTES);
Route route;
JSONObject routesJSONObject;
for (int m = 0; m < routeJSONArray.length(); m++) {
route = new Route(context);
routesJSONObject = routeJSONArray.getJSONObject(m);
JSONArray legsJSONArray;
route.setSummary(routesJSONObject.getString(SUMMARY));
legsJSONArray = routesJSONObject.getJSONArray(LEGS);
JSONObject legJSONObject;
Leg leg;
JSONArray stepsJSONArray;
for (int b = 0; b < legsJSONArray.length(); b++) {
leg = new Leg();
legJSONObject = legsJSONArray.getJSONObject(b);
leg.setDistance(new Distance(legJSONObject.optJSONObject(DISTANCE).optString(TEXT), legJSONObject.optJSONObject(DISTANCE).optLong(VALUE)));
leg.setDuration(new Duration(legJSONObject.optJSONObject(DURATION).optString(TEXT), legJSONObject.optJSONObject(DURATION).optLong(VALUE)));
stepsJSONArray = legJSONObject.getJSONArray(STEPS);
JSONObject stepJSONObject, stepDurationJSONObject, legPolyLineJSONObject, stepStartLocationJSONObject, stepEndLocationJSONObject;
Step step;
String encodedString;
LatLng stepStartLocationLatLng, stepEndLocationLatLng;
for (int i = 0; i < stepsJSONArray.length(); i++) {
stepJSONObject = stepsJSONArray.getJSONObject(i);
step = new Step();
JSONObject stepDistanceJSONObject = stepJSONObject.getJSONObject(DISTANCE);
step.setDistance(new Distance(stepDistanceJSONObject.getString(TEXT), stepDistanceJSONObject.getLong(VALUE)));
stepDurationJSONObject = stepJSONObject.getJSONObject(DURATION);
step.setDuration(new Duration(stepDurationJSONObject.getString(TEXT), stepDurationJSONObject.getLong(VALUE)));
stepEndLocationJSONObject = stepJSONObject.getJSONObject(END_LOCATION);
stepEndLocationLatLng = new LatLng(stepEndLocationJSONObject.getDouble(LATITUDE), stepEndLocationJSONObject.getDouble(LONGITUDE));
step.setEndLocation(stepEndLocationLatLng);
step.setHtmlInstructions(stepJSONObject.getString(HTML_INSTRUCTION));
legPolyLineJSONObject = stepJSONObject.getJSONObject(POLYLINE);
encodedString = legPolyLineJSONObject.getString(POINTS);
step.setPoints(decodePolyLines(encodedString));
stepStartLocationJSONObject = stepJSONObject.getJSONObject(START_LOCATION);
stepStartLocationLatLng = new LatLng(stepStartLocationJSONObject.getDouble(LATITUDE), stepStartLocationJSONObject.getDouble(LONGITUDE));
step.setStartLocation(stepStartLocationLatLng);
leg.addStep(step);
}
route.addLeg(leg);
}
routeList.add(route);
}
return routeList;
} catch (Exception e) {
throw e;
}
Regarding the Step Image there is an HTML instruction and another field called maneuver where according to this field you will choose your image
i hope this helps ;)

I think you can do something like this
LatLng origin = sourcePosition;
LatLng dest = destPosition;
DownloadTask1 downloadTask = new DownloadTask1();
String url = downloadTask.getDirectionsUrl1(origin, dest);
downloadTask.execute(url);
DownloadTask1 class
private class DownloadTask1 extends AsyncTask<String, Void, String> {
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask1 parserTask = new ParserTask1();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
private String getDirectionsUrl1(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false&alternatives=true&units=metric&mode=driving";
//&alternatives=true&units=metric&mode=driving
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
}
downloadUrl() method
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
e.printStackTrace();
//Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
ParserTask1 class
private class ParserTask1 extends AsyncTask<String, Integer, List<List<List<HashMap<String, String>>>>> {
// Parsing the data in non-ui thread
#Override
protected List<List<List<HashMap<String, String>>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<List<HashMap<String, String>>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<List<HashMap<String, String>>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = new PolylineOptions();
PolylineOptions lineOptions1 = null;
MarkerOptions markerOptions = new MarkerOptions();
String distance = "";
String duration = "";
Integer size1 = 0;
Integer size2 = 0;
Integer size3 = 0;
// Log.d(SHETTY, "onPostExecute: result set "+result.size());
List<LatLng> aline1 = new ArrayList<LatLng>();
List<LatLng> aline2 = new ArrayList<LatLng>();
List<LatLng> aline3 = new ArrayList<LatLng>();
if (result != null) {
int i = 0;
Log.d(SHETTY, "onPostExecute: result size " + result.size());
while (i < result.size()) {
// for(int i=0;i<result.size();i++){
//result.size()
//int g= i-1;
points = new ArrayList<LatLng>();
// lineOptions = new PolylineOptions();
// if(i==1){
// }else{
List<List<HashMap<String, String>>> path1 = result.get(i);
for (int s = 0; s < path1.size(); s++) {
Log.d("pathsize1", path1.size() + "");
// Fetching i-th route
List<HashMap<String, String>> path = path1.get(s);
Log.d("pathsize", path.size() + "");
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
lineOptions1 = new PolylineOptions();
HashMap<String, String> point = path.get(j);
// points = new ArrayList<LatLng>();
// if(j==0){ // Get distance from the list
// distance = (String)point.get("distance");
// continue;
// }else if(j==1){ // Get duration from the list
// duration = (String)point.get("duration");
// continue;
// }
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
// Log.d("latlng", position.toString());
points.add(position);
}
// lineOptions.addAll(points);
// lineOptions.width(5);
// lineOptions.color(Color.BLUE);
// map.addPolyline(lineOptions);
}
// }
if (i == 0) {
// line1.addAll(points);
// mMap.addPolyline(line1);
size1 = points.size();
aline1.addAll(points);
} else if (i == 1) {
// line2.addAll(points);
// mMap.addPolyline(line2);
aline2.addAll(points);
size2 = points.size();
} else if (i == 2) {
// line3.addAll(points);
// mMap.addPolyline(line3);
aline3.addAll(points);
size3 = points.size();
}
// Adding all the points in the route to LineOptions
i++;
}
// Drawing polyline in the Google Map for the i-th route
// map.addPolyline(lineOptions);
}
if (size3 != 0)
{
if ((size1 > size2 && size1 > size3)) {
if (size2 > size3) {
PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
PolylineOptions line3 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue));
line1.addAll(aline1);
line2.addAll(aline2);
line3.addAll(aline3);
mMap.addPolyline(line1);
mMap.addPolyline(line2);
mMap.addPolyline(line3);
Log.d(SHETTY, "onPostExecute: 3110 ");
} else {
PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue));
PolylineOptions line3 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
line1.addAll(aline1);
line2.addAll(aline2);
line3.addAll(aline3);
mMap.addPolyline(line1);
mMap.addPolyline(line3);
mMap.addPolyline(line2);
Log.d(SHETTY, "onPostExecute: 3127 ");
}
} else if ((size2 > size1 && size2 > size3)) {
if (size1 > size3) {
PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
PolylineOptions line3 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue));
line1.addAll(aline1);
line2.addAll(aline2);
line3.addAll(aline3);
mMap.addPolyline(line1);
mMap.addPolyline(line2);
mMap.addPolyline(line3);
Log.d(SHETTY, "onPostExecute: 3147 ");
} else {
PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue));
PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
PolylineOptions line3 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
line1.addAll(aline1);
line2.addAll(aline2);
line3.addAll(aline3);
mMap.addPolyline(line2);
mMap.addPolyline(line3);
mMap.addPolyline(line1);
Log.d(SHETTY, "onPostExecute: 3164 ");
}
} else if ((size3 > size1 && size3 > size2)) {
if (size1 > size2) {
PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue));
PolylineOptions line3 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
line1.addAll(aline1);
line2.addAll(aline2);
line3.addAll(aline3);
mMap.addPolyline(line3);
mMap.addPolyline(line1);
mMap.addPolyline(line2);
Log.d(SHETTY, "onPostExecute: 3182 ");
} else {
PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue));
PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
PolylineOptions line3 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
line1.addAll(aline1);
line2.addAll(aline2);
line3.addAll(aline3);
mMap.addPolyline(line3);
mMap.addPolyline(line2);
mMap.addPolyline(line1);
Log.d(SHETTY, "onPostExecute: 3196 ");
}
} else {
System.out.println("ERROR!");
}
}else if(size2!=0)
{
if(size1>size2){
PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue));
line1.addAll(aline1);
line2.addAll(aline2);
mMap.addPolyline(line1);
mMap.addPolyline(line2);
}else
{
PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue));
PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
line1.addAll(aline1);
line2.addAll(aline2);
mMap.addPolyline(line2);
mMap.addPolyline(line1);
}
}
else if(size1!=0){
PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue));
line1.addAll(aline1);
mMap.addPolyline(line1);
}
}
}
Now for parsing JObject create DirectionsJSONParser class
public class DirectionsJSONParser {
/**
* Receives a JSONObject and returns a list of lists containing latitude and
* longitude
*/
public List<List<List<HashMap<String,String>>>> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
List<List<List<HashMap<String,String>>>> routes1 = new ArrayList<List<List<HashMap<String,String>>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
List path1 = new ArrayList<ArrayList<HashMap<String,String>>>();
// Log.d("legs",jLegs.toString());
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
HashMap<String, String> hm1 = new HashMap<String, String>();
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
// Log.d("steps",jSteps.toString());
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
// Log.d("polyline",polyline.toString());
/** Traversing all points */
for(int l=0;l<list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
// Log.d("lat", Double.toString(((LatLng)list.get(l)).latitude));
// Log.d("lng", Double.toString(((LatLng)list.get(l)).longitude));
}
}
path1.add(path);
}
routes1.add(path1);
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routes1;
}
/**
* Method to decode polyline points
* Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
* */
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
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;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
At the end you'll have main route in blue colour and alternatives in grey. Hope it helps.

This should work. Tested on my application.
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArrayRoute = jsonObject.getJSONArray("routes");
JSONObject jsonObjectRoute;
int route = jsonArrayRoute.length();
for (int m = 0; m < route; m++) {
jsonObjectRoute = jsonArrayRoute.getJSONObject(m);
JSONArray jsonArrayLegs;
jsonArrayLegs = jsonObjectRoute.getJSONArray("legs");
JSONObject jsonObjectLegs;
JSONArray jsonArraySteps;
for (int b = 0; b < jsonArrayLegs.length(); b++) {
jsonObjectLegs = jsonArrayLegs.getJSONObject(b);
jsonArraySteps = jsonObjectLegs.getJSONArray("steps");
JSONObject jsonObjectSteps, jsonObjectLegPolyline;
String[] polylineArray = new String[jsonArraySteps.length()];
for (int i = 0; i < jsonArraySteps.length(); i++) {
jsonObjectSteps = jsonArraySteps.getJSONObject(i);
jsonObjectLegPolyline = jsonObjectSteps.getJSONObject("polyline");
String polygone = jsonObjectLegPolyline.getString("points");
polylineArray[i] = polygone;
}
int count2 = polylineArray.length;
for (int i = 0; i < count2; i++) {
mGoogleMap.addPolyline((new PolylineOptions())
.color(Color.BLUE)
.width(10)
.clickable(true)
.addAll(PolyUtil.decode(polylineArray[i])));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Related

How can I get array of available routing LatLng between Source LatLng and destination LatLng?

I wanted to add some checkpoints(Marker) into Google map between the Source and destination as per available route in my Android App.
Check this Google Maps tutorial HERE.
On the step 4, you parse a JSON which contains the different routes. From each route you can get the points with Lat and Lng values.
public class PathToDestination {
private GoogleMap mMap;
private Context context;
private static final String API_KEY = "your key";
private String pathColor = "#05b1fb";//default blue color
private int pathWidth = 5;//default is 5
private Polyline line;
private PolylineOptions polylineOptions;
public PathToDestination(Context context, GoogleMap mMap) {
this.context = context;
this.mMap = mMap;
}
public void setPathColor(String pathColor) {
this.pathColor = pathColor;
}
public void setPathWidth(int pathWidth) {
this.pathWidth = pathWidth;
}
public void drawPathBetween(#MapManager.PathMode int mode, double sourcelat, double sourcelog, double destlat, double destlog) {
drawPathBetween(mode, sourcelat, sourcelog, destlat, destlog, null);
}
public void drawPathBetween(#MapManager.PathMode int mode, double sourcelat, double sourcelog, double destlat, double destlog, MapModel[] waypoints) {
String urlStr = makeURL(mode, sourcelat, sourcelog, destlat, destlog, waypoints);
new ConnectAsyncTask(urlStr).execute();
}
/*private String makeURL(double sourcelat, double sourcelog, double destlat, double destlog) {
return makeURL(sourcelat, sourcelog, destlat, destlog, );
}*/
private String makeURL(#MapManager.PathMode int mode, double sourcelat, double sourcelog, double destlat, double destlog, MapModel... waypoints) {
StringBuilder urlString = new StringBuilder();
urlString.append("https://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append(Double.toString(sourcelat));
urlString.append(",");
urlString.append(Double.toString(sourcelog));
if (waypoints != null && waypoints.length > 0) {
urlString.append("&waypoints=");// waypoints
for (int i = 0; i < waypoints.length; i++) {
MapModel coordinate = waypoints[i];
urlString.append(coordinate.getLatitude());
urlString.append(",");
urlString.append(coordinate.getLongitude());
if (i < waypoints.length - 1) {
urlString.append("|");
}
}
}
urlString.append("&destination=");// to
urlString.append(Double.toString(destlat));
urlString.append(",");
urlString.append(Double.toString(destlog));
urlString.append("&sensor=false");
urlString.append("&mode=" + mode);
urlString.append("&alternatives=true");
urlString.append("&key=" + API_KEY);
return urlString.toString();
}
private void drawPath(String result) {
try {
//Tranform the string into a json object
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = null;
if (polylineOptions == null) {
polylineOptions = new PolylineOptions()
.width(pathWidth)
.color(Color.parseColor(pathColor)) //Google maps blue color
.geodesic(true);
}
list = decodePoly(encodedString);
polylineOptions.addAll(list);
if (line == null) {
line = mMap.addPolyline(polylineOptions);
}
line.setPoints(list);
/*
for(int z = 0; z<list.size()-1;z++){
LatLng src= list.get(z);
LatLng dest= list.get(z+1);
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude))
.width(2)
.color(Color.BLUE).geodesic(true));
}
*/
} catch (JSONException e) {
e.printStackTrace();
}
}
public void drawPathFromEncodedPolyline(String encodedPolyline) {
// try {
//Tranform the string into a json object
// final JSONObject json = new JSONObject(result);
// JSONArray routeArray = json.getJSONArray("routes");
// JSONObject routes = routeArray.getJSONObject(0);
// JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
// String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedPolyline);
Polyline line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(5)
.color(Color.parseColor("#05b1fb"))//Google maps blue color
.geodesic(true)
);
/*
for(int z = 0; z<list.size()-1;z++){
LatLng src= list.get(z);
LatLng dest= list.get(z+1);
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude))
.width(2)
.color(Color.BLUE).geodesic(true));
}
*/
// } catch (JSONException e) {
// e.printStackTrace();
// }
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
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;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
private class ConnectAsyncTask extends AsyncTask<Void, Void, String> {
private ProgressDialog progressDialog;
String url;
ConnectAsyncTask(String urlPass) {
url = urlPass;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 &&
!((Activity) context).isDestroyed()) ||
!((Activity) context).isFinishing()) {
progressDialog = new ProgressDialog(context);
// progressDialog.setMessage("Fetching route, Please wait...");
// progressDialog.setIndeterminate(true);
// progressDialog.show();
}
}
#Override
protected String doInBackground(Void... params) {
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
URL url = new URL(this.url);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
return jsonResults.toString();
} catch (IOException e) {
return jsonResults.toString();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return jsonResults.toString();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (progressDialog != null) {
progressDialog.hide();
}
if (result != null) {
drawPath(result);
}
}
}
public void clearRoute() {
if (line != null) {
line.remove();
}
line = null;
polylineOptions = null;
}
}
Here MapModel is an interface
public interface MapModel {
double getLatitude();
double getLongitude();
}
If you want the list of LatLng you can easily get that from
drawPathFromEncodedPolyline(String encodedPolyline)
method.
You can look here for other map functions.

Draw Path From Lat/Long

I want to draw path of my lat long position on a map from SQLite. Is it possible and can anyone help me with this on Android? I've attached my map activity for location.
You can try this
PolylineOptions rectOptions = new PolylineOptions()
.add(new LatLng(37.35, -122.0))
.add(new LatLng(37.45, -122.0)) // North of the previous point, but at the same longitude
.add(new LatLng(37.45, -122.2)) // Same latitude, and 30km to the west
.add(new LatLng(37.35, -122.2)) // Same longitude, and 16km to the south
.add(new LatLng(37.35, -122.0)); // Closes the polyline.
// Get back the mutable Polyline
Polyline polyline = myMap.addPolyline(rectOptions);
or for database
Cursor cursor = database,getData("your query");
PolylineOptions rectOptions = new PolylineOptions();
if(cursor!=null && cursor.getCount()>0 && cursor.moveToFirst())
{
do
{
String lt = cursor.getString(curor.getColumnIndex("columnName"));
double lat = Double.parseDouble(lt);
String ln = cursor.getString(curor.getColumnIndex("columnName"));
double lng = Double.parseDouble(ln);
rectOptions.add(new LatLng(lat, lng)); // Closes the polyline.
// Get back the mutable Polyline
}while(cursor.moveToNext());
}
Polyline polyline = myMap.addPolyline(rectOptions);
**Create Seperate class**
class DirectionsJSONParser {
/**
* Receives a JSONObject and returns a list of lists containing latitude and longitude
*/
public List<List<HashMap<String, String>>> parse(JSONObject jObject) {
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONObject jDistance = null;
JSONArray jSteps = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for (int i = 0; i < jRoutes.length(); i++) {
jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for (int j = 0; j < jLegs.length(); j++) {
/** Getting distance from the json data */
jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
HashMap<String, String> hmDistance = new HashMap<String, String>();
hmDistance.put("distance", jDistance.getString("value"));
jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
/** Adding distance object to the path */
path.add(hmDistance);
/** Traversing all steps */
for (int k = 0; k < jSteps.length(); k++) {
String polyline = "";
polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
/** Traversing all points */
for (int l = 0; l < list.size(); l++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng) list.get(l)).latitude));
hm.put("lng", Double.toString(((LatLng) list.get(l)).longitude));
path.add(hm);
}
}
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
}
return routes;
}
/**
* Method to decode polyline points
* Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
*/
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
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;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
- **In Activtiy**
private String getDirectionsUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String> {
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url1) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(url1[0]);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d(TAG, e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
} catch (Exception e) {
Log.d(TAG, e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points;
PolylineOptions lineOptions = null;
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
if (j == 0) { // Get distance from the list
String dist = point.get("distance");
if(dist!=null && dist.length()>0) {
int distInt = Integer.parseInt(dist);
sumDistance += distInt;
}
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(10);
lineOptions.color(Color.BLUE);
}
mGoogleMap.addPolyline(lineOptions);
if (true) {
// Drawing polyline in the Google Map for the i-th route
mGoogleMap.addPolyline(lineOptions);
}
//Log.d(TAG, "map: " + map + " lineoptions: " + lineOptions);
}
}
calling:
String url = getDirectionsUrl(position, position1);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);

Adding polylines in asynctask android

i'm having performance issues adding polylines and thought that maybe it'll be possible to add them in a separate class extending AsyncTask. However as i learned that UI elements can't be added in such way (and polylines are UI elements).
Why i'm having performance issues while drawing polylines? Well, my polylines are drawn not from pos A to pos B but from my current location to destination (which is hardcoded for the sake of application atm). So the polylines are drawn when onLocationChange listener is executed and thus my application requires lots of proccessing power.
Any ideas how to use AsyncTask on this occasion?
This is the main class:
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// Get positions!
currentPOS = new LatLng(arg0.getLatitude(), arg0.getLongitude());
LatLng dst = new LatLng(58.378249, 26.714673);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(currentPOS, 13);
mMap.animateCamera(yourLocation);
mMap.addMarker(new MarkerOptions().position(dst).title("SCHOOL!"));
/*
// Remove comments to add marker to Liivi 2!
mMap.addMaker(new MarkerOptions().position(currentPOS).title("My POS"));
*/
if (currentPOS != null) {
//This is supposed to show directions
DirectionAPI directionAPI = new DirectionAPI(currentPOS, dst);
GoogleResponse googleResponse = null;
try {
googleResponse = (GoogleResponse) directionAPI.execute().get();
} catch (InterruptedException e) {
Log.e("CATCH","INTERRUPDED");
e.printStackTrace();
} catch (ExecutionException e) {
Log.e("CATCH","EXECUTIONEXCEPTION");
e.printStackTrace();
}
if (googleResponse.isOk()){
DrivingDirection drivingDirection = new DrivingDirection(googleResponse.getJsonObject());
polyline = drivingDirection.getTotalPolyline();
new drawPath(mMap,polyline).execute();
}
}
}
});
This is the Async for path drawing (which will result in an error due to UI conflict):
import android.graphics.Color;
import android.os.AsyncTask;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import java.util.ArrayList;
/**
* Created by Kevin on 7.10.2015.
*/
public class drawPath extends AsyncTask{
private static ArrayList<LatLng> polyline;
private static GoogleMap mMap;
public drawPath(GoogleMap map, ArrayList<LatLng> polyline){
this.mMap = map;
this.polyline = polyline;
}
#Override
protected Object doInBackground(Object[] params) {
for (int i = 0; i < polyline.size() - 1; i++) {
LatLng src = polyline.get(i);
LatLng dest = polyline.get(i + 1);
// mMap is the Map Object
Polyline line = mMap.addPolyline(
new PolylineOptions().add(
new LatLng(src.latitude, src.longitude),
new LatLng(dest.latitude,dest.longitude)
).width(2).color(Color.BLUE).geodesic(true)
);
}
return null;
}
}
I solved this issue in a way that i did not add every polyline map separately but whole polyline. For example, before i had my location about 4km away from destination and it had 280 polylines between. On every onLocationChange these polylines were drawn one-by-one to map. Now they're all added at once - AsyncTask will create polylines in the background and in the post-execute they will be added.
#Override
protected Object doInBackground(Object[] params) {
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int z = 0; z < polyline.size(); z++) {
LatLng point = polyline.get(z);
options.add(point);
}
return options;
}
protected void onPostExecute(Object result) {
Polyline line = mMap.addPolyline((PolylineOptions) result);
}
you can use this code
ublic class DrawrootTask extends AsyncTask<String, String, String> {
private Context context;
public static boolean flagCompleted = false;
private GoogleMap googleMap;
private double source_lat = 0.0;
private double source_long = 0.0;
private double dest_lat = 0.0;
private double dest_long = 0.0;
Userdata userdata;
String tag = "DrawRootTask";
private ProgressDialog progressDialog;
public static double dist, time;
private Polyline line;
String distanceText = "";
String durationText = "";
public DrawrootTask(Context context, LatLng source, LatLng destination,
GoogleMap googleMap) {
source_lat = source.latitude;
source_long = source.longitude;
dest_lat = destination.latitude;
dest_long = destination.longitude;
this.googleMap = googleMap;
this.context = context;
userdata = Userdata.getinstance(context);
}
protected void onPreExecute() {
// // TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage(context.getResources().getString(
R.string.please_wait));
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String json = "";
// constructor
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
HashMap<String, String> keyValue = new HashMap<String, String>();
urlString.append("?origin=");// from
urlString.append(Double.toString(source_lat));
urlString.append(",");
urlString.append(Double.toString(source_long));
urlString.append("&destination=");// to
urlString.append(Double.toString(dest_lat));
urlString.append(",");
urlString.append(Double.toString(dest_long));
urlString.append("&sensor=false&mode=driving&alternatives=true");
// defaultHttpClient
String url = urlString.toString();
FetchUrl fetchurl = new FetchUrl();
json = fetchurl.fetchUrl(url, keyValue);
Log.e("Buffer Error", json);
return json;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
progressDialog.dismiss();
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes
.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);
for (int z = 0; z < list.size() - 1; z++) {
LatLng src = list.get(z);
LatLng dest = list.get(z + 1);
line = googleMap.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude),
new LatLng(dest.latitude, dest.longitude))
// .width(8).color(Color.BLUE).geodesic(true));
.width(8)
.color(context.getResources().getColor(
R.color.actionbar_color)).geodesic(true));
Log.i("draw root", "" + "" + line.toString());
}
JSONArray legs = routes.getJSONArray("legs");
JSONObject steps = legs.getJSONObject(0);
JSONObject duration = steps.getJSONObject("duration");
JSONObject distance = steps.getJSONObject("distance");
distanceText = distance.getString("text");
durationText = duration.getString("text");
Log.i("draw root", "" + distance.toString());
dist = Double.parseDouble(distance.getString("text").replaceAll(
"[^\\.0123456789]", ""));
time = Double.parseDouble(duration.getString("text").replaceAll(
"[^\\.0123456789]", ""));
userdata.setDistance(distanceText);
userdata.setTime(durationText);
Log.d(tag, "distace is " + dist + " time is " + time);
flagCompleted = true;
} catch (JSONException e) {
Log.d("draw root", "" + e);
}
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
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;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}

Android - How to remove straight line from multiple routes on Google Maps API v2

I have app which set multiple routes on the map.
The problem is when I put two points in the map, he get the suggested routes but with one extra straight line.
I found a solution. I just get the main tag for polyline - overview_polyline
In the code are the new changes :)
pic multiple routes - alternatives=true - I set just one road
pic - if I set alternatives=false in xml link, the straight line disappears.
In the xml everything is fine.
I looked in to the 2 xml files with alternatives=false and alternatives=true but there are identical.
link to XML file
Thanks in advance.
this code display the information:
//Polyline
private class GetRouteTask extends AsyncTask<String, Void, String> {
String response = "";
#Override
protected String doInBackground(String... urls) {
//Get All Route values
v2GetRouteDirection = new GMapV2Direction();
document = v2GetRouteDirection.getDocument(latLngFrom, latLngTo, GMapV2Direction.MODE_DRIVING);
response = "Success";
return response;
}
#Override
protected void onPostExecute(String result) {
if(document != null){
ArrayList<LatLng> directionPoint = v2GetRouteDirection.getDirection(document);
PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
// Adding route on the map
map.addPolyline(rectLine);
}
}
}
this code get the tag information:
public class GMapV2Direction {
public GMapV2Direction(){}
public final static String MODE_DRIVING = "driving";
public final static String MODE_WALKING = "walking";
public static String error = null;
public Document getDocument(LatLng start, LatLng end, String mode) {
String url = "http://maps.googleapis.com/maps/api/directions/xml?"
+ "origin=" + start.latitude + "," + start.longitude
+ "&destination=" + end.latitude + "," + end.longitude
+ "&sensor=false&units=metric&mode=driving&alternatives=true";
////////////////
//Set TimeOuts
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
try {
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet, localContext);
InputStream in = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
return doc;
}
catch (ClientProtocolException e) {
error = "some";
e.printStackTrace();
} catch (IOException e) {
error = "some";
e.printStackTrace();
}
catch (Exception e) {
error = "some";
e.printStackTrace();
}
return null;
}
public ArrayList<LatLng> getDirection (Document doc) {
NodeList error = doc.getElementsByTagName("status");
int p;
Node error1 = null;
//взема последнич елемент на таг
for(p = 0;p<error.getLength();p++){
error1 = error.item(p);
}
if(p==p){
p--;
}
LatLng latLngZero = new LatLng(0.0, 0.0);
ArrayList<LatLng> list = new ArrayList<LatLng>();
list.add(latLngZero);
ArrayList<LatLng> listGeopoints = null;
if(error1.getFirstChild().getTextContent().equals("OK")) {
//new
NodeList routeTag,nl3;
listGeopoints = new ArrayList<LatLng>();
//get tag route
routeTag = doc.getElementsByTagName("route");
if (routeTag.getLength() > 0) {
//get first eelemnt of route
Element routeElement = (Element) routeTag.item(0);
//get tag overview_polyline
NodeList polylineList = routeElement.getElementsByTagName("overview_polyline");
Node node1 = polylineList.item(0);
nl3 = node1.getChildNodes();
Node latNode = nl3.item(getNodeIndex(nl3, "points"));
List<LatLng> arr = decodePoly(latNode.getTextContent());
for (int j = 0; j < arr.size(); j++) {
listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude));
}
}
}
//////////////
else{
return list;
}
return listGeopoints;
}
private int getNodeIndex(NodeList nl, String nodename) {
for(int i = 0 ; i < nl.getLength() ; i++) {
if(nl.item(i).getNodeName().equals(nodename))
return i;
}
return -1;
}
private ArrayList<LatLng> decodePoly(String encoded) {
ArrayList<LatLng> poly = new ArrayList<LatLng>();
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;
LatLng position = new LatLng((double) lat / 1E5, (double) lng / 1E5);
poly.add(position);
}
return poly;
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.google.android.gms.maps.model.LatLng;
public class DirectionsJSONParser {
public List<List<List<HashMap<String,String>>>> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
List<List<List<HashMap<String,String>>>> routes1 = new ArrayList<List<List<HashMap<String,String>>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
List path1 = new ArrayList<ArrayList<HashMap<String,String>>>();
// Log.d("legs",jLegs.toString());
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
HashMap<String, String> hm1 = new HashMap<String, String>();
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
// Log.d("steps",jSteps.toString());
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
// Log.d("polyline",polyline.toString());
/** Traversing all points */
for(int l=0;l<list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
// Log.d("lat", Double.toString(((LatLng)list.get(l)).latitude));
// Log.d("lng", Double.toString(((LatLng)list.get(l)).longitude));
}
}
path1.add(path);
}
routes1.add(path1);
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routes1;
}
/**
* Method to decode polyline points
* Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
* */
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
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;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
Faced similar problem and soled it by using addall() method for polylineoptions object to draw line on map directly using array list of latlng's.
Cannot confirm but trying this code might help
Polyline
private class GetRouteTask extends AsyncTask<String, Void, String> {
String response = "";
#Override
protected String doInBackground(String... urls) {
//Get All Route values
v2GetRouteDirection = new GMapV2Direction();
document = v2GetRouteDirection.getDocument(latLngFrom, latLngTo, GMapV2Direction.MODE_DRIVING);
response = "Success";
return response;
}
#Override
protected void onPostExecute(String result) {
if(document != null){
ArrayList<LatLng> directionPoint = v2GetRouteDirection.getDirection(document);
PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);
rectLine.addall(directionPoint);
// Adding route on the map
map.addPolyline(rectLine);
}
}
}
LatLng origin = new latlng(type your starting point latitude and longtitude);
LatLng dest = new latlng(type your ending point latitude and longtitude);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
private String getDirectionsUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false&alternatives=true&units=metric&mode=driving";
//&alternatives=true&units=metric&mode=driving
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String> {
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, List<List<List<HashMap<String, String>>>>> {
// Parsing the data in non-ui thread
#Override
protected List<List<List<HashMap<String, String>>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<List<HashMap<String, String>>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<List<HashMap<String, String>>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = new PolylineOptions();
PolylineOptions lineOptions1 = null;
MarkerOptions markerOptions = new MarkerOptions();
String distance = "";
String duration = "";
Log.d("resultsize", result.size() + "");
int i = 0;
while (i < result.size()) {
// for(int i=0;i<result.size();i++){
//result.size()
//int g= i-1;
points = new ArrayList<LatLng>();
// lineOptions = new PolylineOptions();
// if(i==1){
// }else{
List<List<HashMap<String, String>>> path1 = result.get(i);
for (int s = 0; s < path1.size(); s++) {
Log.d("pathsize1", path1.size() + "");
// Fetching i-th route
List<HashMap<String, String>> path = path1.get(s);
Log.d("pathsize", path.size() + "");
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
lineOptions1 = new PolylineOptions();
HashMap<String, String> point = path.get(j);
// points = new ArrayList<LatLng>();
// if(j==0){ // Get distance from the list
// distance = (String)point.get("distance");
// continue;
// }else if(j==1){ // Get duration from the list
// duration = (String)point.get("duration");
// continue;
// }
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
// Log.d("latlng", position.toString());
points.add(position);
}
// lineOptions.addAll(points);
// lineOptions.width(5);
// lineOptions.color(Color.BLUE);
// map.addPolyline(lineOptions);
}
// }
if (i == 0) {
PolylineOptions line1 = new PolylineOptions();
line1.addAll(points);
line1.width(5);
line1.color(Color.RED);
map.addPolyline(line1);
} else if (i == 1) {
PolylineOptions line2 = new PolylineOptions();
line2.addAll(points);
line2.width(5);
line2.color(Color.BLUE);
map.addPolyline(line2);
} else if (i == 2) {
PolylineOptions line3 = new PolylineOptions();
line3.addAll(points);
line3.width(5);
line3.color(Color.GREEN);
map.addPolyline(line3);
}
// Adding all the points in the route to LineOptions
i++;
//
}
// Drawing polyline in the Google Map for the i-th route
// map.addPolyline(lineOptions);
}
}

Android show driving direction route between two geopoints

I have googled for 2-3 days now, but I am not able to get the perfect solution for my problem.
I need to show the route between two geo points (Not a straight line but need to show driving direction kind of route)
but I am not able to find any solution to this.
I had come across the solution in this question.
But I guess the solution also not working. If you can help me out that will be great.
I found the solution Look for answer bellow...
I am using this
String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
mHandler.sendEmptyMessage(0);
and in a handler
MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.add(mapOverlay);
here is roadprovider.java
package com.singPost;
import java.io.IOException;
import java.io.InputStream;
import java.util.Stack;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class RoadProvider
{
public static Road getRoute(InputStream is)
{
KMLHandler handler = new KMLHandler();
try {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(is, handler);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return handler.mRoad;
}
public static String getUrl(double fromLat, double fromLon, double toLat, double toLon)
{
// connect to map web service
StringBuffer urlString = new StringBuffer();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");// from
urlString.append(Double.toString(fromLat));
urlString.append(",");
urlString.append(Double.toString(fromLon));
urlString.append("&daddr=");// to
urlString.append(Double.toString(toLat));
urlString.append(",");
urlString.append(Double.toString(toLon));
urlString.append("&ie=UTF8&0&om=0&output=kml");
return urlString.toString();
}
}
class KMLHandler extends DefaultHandler {
Road mRoad;
boolean isPlacemark;
boolean isRoute;
boolean isItemIcon;
private Stack mCurrentElement = new Stack();
private String mString;
public KMLHandler() {
mRoad = new Road();
}
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
mCurrentElement.push(localName);
if (localName.equalsIgnoreCase("Placemark")) {
isPlacemark = true;
mRoad.mPoints = addPoint(mRoad.mPoints);
} else if (localName.equalsIgnoreCase("ItemIcon")) {
if (isPlacemark)
isItemIcon = true;
}
mString = new String();
}
public void characters(char[] ch, int start, int length)
throws SAXException {
String chars = new String(ch, start, length).trim();
mString = mString.concat(chars);
}
public void endElement(String uri, String localName, String name)
throws SAXException {
if (mString.length() > 0) {
if (localName.equalsIgnoreCase("name")) {
if (isPlacemark) {
isRoute = mString.equalsIgnoreCase("Route");
if (!isRoute) {
mRoad.mPoints[mRoad.mPoints.length - 1].mName = mString;
}
} else {
mRoad.mName = mString;
}
} else if (localName.equalsIgnoreCase("color") && !isPlacemark) {
mRoad.mColor = Integer.parseInt(mString, 16);
} else if (localName.equalsIgnoreCase("width") && !isPlacemark) {
mRoad.mWidth = Integer.parseInt(mString);
} else if (localName.equalsIgnoreCase("description")) {
if (isPlacemark) {
String description = cleanup(mString);
if (!isRoute)
mRoad.mPoints[mRoad.mPoints.length - 1].mDescription = description;
else
mRoad.mDescription = description;
}
} else if (localName.equalsIgnoreCase("href")) {
if (isItemIcon) {
mRoad.mPoints[mRoad.mPoints.length - 1].mIconUrl = mString;
}
} else if (localName.equalsIgnoreCase("coordinates")) {
if (isPlacemark) {
if (!isRoute) {
String[] xyParsed = split(mString, ",");
double lon = Double.parseDouble(xyParsed[0]);
double lat = Double.parseDouble(xyParsed[1]);
mRoad.mPoints[mRoad.mPoints.length - 1].mLatitude = lat;
mRoad.mPoints[mRoad.mPoints.length - 1].mLongitude = lon;
} else {
String[] coodrinatesParsed = split(mString, " ");
int lenNew = coodrinatesParsed.length;
int lenOld = mRoad.mRoute.length;
double[][] temp = new double[lenOld + lenNew][2];
for (int i = 0; i < lenOld; i++) {
temp[i] = mRoad.mRoute[i];
}
for (int i = 0; i < lenNew; i++) {
String[] xyParsed = split(coodrinatesParsed[i], ",");
for (int j = 0; j < 2 && j < xyParsed.length; j++)
temp[lenOld + i][j] = Double
.parseDouble(xyParsed[j]);
}
mRoad.mRoute = temp;
}
}
}
}
mCurrentElement.pop();
if (localName.equalsIgnoreCase("Placemark")) {
isPlacemark = false;
if (isRoute)
isRoute = false;
} else if (localName.equalsIgnoreCase("ItemIcon")) {
if (isItemIcon)
isItemIcon = false;
}
}
private String cleanup(String value) {
String remove = "<br/>";
int index = value.indexOf(remove);
if (index != -1)
value = value.substring(0, index);
remove = " ";
index = value.indexOf(remove);
int len = remove.length();
while (index != -1) {
value = value.substring(0, index).concat(
value.substring(index + len, value.length()));
index = value.indexOf(remove);
}
return value;
}
public Point2[] addPoint(Point2[] points)
{
Point2[] result = new Point2[points.length + 1];
for (int i = 0; i < points.length; i++)
result[i] = points[i];
result[points.length] = new Point2();
return result;
}
private static String[] split(String strString, String strDelimiter)
{
String[] strArray;
int iOccurrences = 0;
int iIndexOfInnerString = 0;
int iIndexOfDelimiter = 0;
int iCounter = 0;
if (strString == null)
{
throw new IllegalArgumentException("Input string cannot be null.");
}
if (strDelimiter.length() <= 0 || strDelimiter == null)
{
throw new IllegalArgumentException("Delimeter cannot be null or empty.");
}
if (strString.startsWith(strDelimiter))
{
strString = strString.substring(strDelimiter.length());
}
if (!strString.endsWith(strDelimiter))
{
strString += strDelimiter;
}
while ((iIndexOfDelimiter = strString.indexOf(strDelimiter,
iIndexOfInnerString)) != -1)
{
iOccurrences += 1;
iIndexOfInnerString = iIndexOfDelimiter + strDelimiter.length();
}
strArray = new String[iOccurrences];
iIndexOfInnerString = 0;
iIndexOfDelimiter = 0;
while ((iIndexOfDelimiter = strString.indexOf(strDelimiter,
iIndexOfInnerString)) != -1)
{
strArray[iCounter] = strString.substring(iIndexOfInnerString,
iIndexOfDelimiter);
iIndexOfInnerString = iIndexOfDelimiter + strDelimiter.length();
iCounter += 1;
}
return strArray;
}
}
Hey guys The Problem in the Link I found it
Google has stopped to give the api response in KML format
also the solution for the same is here
this works greate for me:
it's not my code, i took it from a great answer at stackoverflow but i can't find this answer now, so here is the code:
add this class to your project:
package ...;
import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.google.android.gms.maps.model.LatLng;
import android.content.Context;
import android.util.Log;
public class GMapV2Direction {
public final static String MODE_DRIVING = "driving";
public final static String MODE_WALKING = "walking";
public GMapV2Direction() {
}
public Document getDocument(LatLng start, LatLng end, String mode) {
String url = "http://maps.googleapis.com/maps/api/directions/xml?"
+ "origin=" + start.latitude + "," + start.longitude
+ "&destination=" + end.latitude + "," + end.longitude
+ "&sensor=false&units=metric&mode=driving";
Log.d("url", url);
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost, localContext);
InputStream in = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(in);
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String getDurationText(Document doc) {
try {
NodeList nl1 = doc.getElementsByTagName("duration");
Node node1 = nl1.item(0);
NodeList nl2 = node1.getChildNodes();
Node node2 = nl2.item(getNodeIndex(nl2, "text"));
Log.i("DurationText", node2.getTextContent());
return node2.getTextContent();
} catch (Exception e) {
return "0";
}
}
public int getDurationValue(Document doc) {
try {
NodeList nl1 = doc.getElementsByTagName("duration");
Node node1 = nl1.item(0);
NodeList nl2 = node1.getChildNodes();
Node node2 = nl2.item(getNodeIndex(nl2, "value"));
Log.i("DurationValue", node2.getTextContent());
return Integer.parseInt(node2.getTextContent());
} catch (Exception e) {
return -1;
}
}
public String getDistanceText(Document doc) {
/*
* while (en.hasMoreElements()) { type type = (type) en.nextElement();
*
* }
*/
try {
NodeList nl1;
nl1 = doc.getElementsByTagName("distance");
Node node1 = nl1.item(nl1.getLength() - 1);
NodeList nl2 = null;
nl2 = node1.getChildNodes();
Node node2 = nl2.item(getNodeIndex(nl2, "value"));
Log.d("DistanceText", node2.getTextContent());
return node2.getTextContent();
} catch (Exception e) {
return "-1";
}
/*
* NodeList nl1; if(doc.getElementsByTagName("distance")!=null){ nl1=
* doc.getElementsByTagName("distance");
*
* Node node1 = nl1.item(nl1.getLength() - 1); NodeList nl2 = null; if
* (node1.getChildNodes() != null) { nl2 = node1.getChildNodes(); Node
* node2 = nl2.item(getNodeIndex(nl2, "value")); Log.d("DistanceText",
* node2.getTextContent()); return node2.getTextContent(); } else return
* "-1";} else return "-1";
*/
}
public int getDistanceValue(Document doc) {
try {
NodeList nl1 = doc.getElementsByTagName("distance");
Node node1 = null;
node1 = nl1.item(nl1.getLength() - 1);
NodeList nl2 = node1.getChildNodes();
Node node2 = nl2.item(getNodeIndex(nl2, "value"));
Log.i("DistanceValue", node2.getTextContent());
return Integer.parseInt(node2.getTextContent());
} catch (Exception e) {
return -1;
}
/*
* NodeList nl1 = doc.getElementsByTagName("distance"); Node node1 =
* null; if (nl1.getLength() > 0) node1 = nl1.item(nl1.getLength() - 1);
* if (node1 != null) { NodeList nl2 = node1.getChildNodes(); Node node2
* = nl2.item(getNodeIndex(nl2, "value")); Log.i("DistanceValue",
* node2.getTextContent()); return
* Integer.parseInt(node2.getTextContent()); } else return 0;
*/
}
public String getStartAddress(Document doc) {
try {
NodeList nl1 = doc.getElementsByTagName("start_address");
Node node1 = nl1.item(0);
Log.i("StartAddress", node1.getTextContent());
return node1.getTextContent();
} catch (Exception e) {
return "-1";
}
}
public String getEndAddress(Document doc) {
try {
NodeList nl1 = doc.getElementsByTagName("end_address");
Node node1 = nl1.item(0);
Log.i("StartAddress", node1.getTextContent());
return node1.getTextContent();
} catch (Exception e) {
return "-1";
}
}
public String getCopyRights(Document doc) {
try {
NodeList nl1 = doc.getElementsByTagName("copyrights");
Node node1 = nl1.item(0);
Log.i("CopyRights", node1.getTextContent());
return node1.getTextContent();
} catch (Exception e) {
return "-1";
}
}
public ArrayList<LatLng> getDirection(Document doc) {
NodeList nl1, nl2, nl3;
ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
nl1 = doc.getElementsByTagName("step");
if (nl1.getLength() > 0) {
for (int i = 0; i < nl1.getLength(); i++) {
Node node1 = nl1.item(i);
nl2 = node1.getChildNodes();
Node locationNode = nl2
.item(getNodeIndex(nl2, "start_location"));
nl3 = locationNode.getChildNodes();
Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
double lat = Double.parseDouble(latNode.getTextContent());
Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
double lng = Double.parseDouble(lngNode.getTextContent());
listGeopoints.add(new LatLng(lat, lng));
locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
nl3 = locationNode.getChildNodes();
latNode = nl3.item(getNodeIndex(nl3, "points"));
ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
for (int j = 0; j < arr.size(); j++) {
listGeopoints.add(new LatLng(arr.get(j).latitude, arr
.get(j).longitude));
}
locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
nl3 = locationNode.getChildNodes();
latNode = nl3.item(getNodeIndex(nl3, "lat"));
lat = Double.parseDouble(latNode.getTextContent());
lngNode = nl3.item(getNodeIndex(nl3, "lng"));
lng = Double.parseDouble(lngNode.getTextContent());
listGeopoints.add(new LatLng(lat, lng));
}
}
return listGeopoints;
}
private int getNodeIndex(NodeList nl, String nodename) {
for (int i = 0; i < nl.getLength(); i++) {
if (nl.item(i).getNodeName().equals(nodename))
return i;
}
return -1;
}
private ArrayList<LatLng> decodePoly(String encoded) {
ArrayList<LatLng> poly = new ArrayList<LatLng>();
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;
LatLng position = new LatLng((double) lat / 1E5, (double) lng / 1E5);
poly.add(position);
}
return poly;
}
}
then use this class for your needs:
for example to draw directions:
md = new GMapV2Direction();
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
Document doc = md.getDocument(sourcePosition, destPosition,
GMapV2Direction.MODE_DRIVING);
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(3).color(
Color.RED);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
Polyline polylin = mMap.addPolyline(rectLine);
the sourcePosition, destPosition are from the LatLng type, and you give them the wanted points. i wrote here parts from my code that i think could help, Any question is welcome.

Categories

Resources