Get Driving Directions Using Google Maps API V2

Step by Step Driving instructions using google maps API v2 and directions API?

Try this http://maps.googleapis.com/maps/api/directions/json?origin=5th%20Ave&destination=Times%20Square&mode=bicycling&sensor=false

Here ,in the json response there is a tag:maneuver you can use this for your need

Is there a way to show road directions in Google Map API v2?

Try this solution here. You can get driving or walking direction on V2.

Google Map API v2 - Get Driving Distance from Current Location to Known Locations

Here's an update of your existing code:

// Executes in UI thread, after the parsing process
@Override
protected void onPostExecute(List<List<HashMap<String, String>>> result)
{
if (result.size() < 1)
{
Toast.makeText(getActivity(), "No Points", Toast.LENGTH_SHORT).show();
return;
}

TextView tv1 = (TextView) getActivity().findViewById(R.id.location1);
TextView tv2 = (TextView) getActivity().findViewById(R.id.location2);
TextView tv3 = (TextView) getActivity().findViewById(R.id.location3);
TextView tv4 = (TextView) getActivity().findViewById(R.id.location4);

TextView[] views = {tv1, tv2, tv3, tv4};


// Traversing through all the routes
for (int i = 0; i < result.size(); i++)
{
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
String distance = "No distance";

// 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)
{
distance = point.get("distance");
continue;
}
}

// Set text
views[i].setText(distance);
}
}

This code makes a not-so-good assumption: It assumes that the size of result is the same size as views, which in your case should be 4. When you run this code, you may get an IndexOutOfBounds error if you have more than 4 results (which shouldn't happen). Eventually you will want to verify that the size of result is 4, or the number of TextView's you have. If you have any questions or this doesn't work right, just let me know :)

EDIT: To get all distances at once, you can modify your DownloadTask to take in multiple URL's.

Change class definition:

private class DownloadTask extends AsyncTask<String, Void, ArrayList<String>>

This says that your background operation will return a list of String's.

Modified doInBackground(), which now can process multiple URL's:

// Downloading data in non-ui thread
@Override
protected ArrayList<String> doInBackground(String... urlList)
{
try
{
ArrayList<String> returnList = new ArrayList<String>();
for(String url : urlList)
{
// Fetching the data from web service
String data = Locations.this.downloadUrl(url);
returnList.add(data);
}

return returnList;
}
catch (Exception e)
{
Log.d("Background Task", e.toString());
return null; // Failed, return null
}
}

Then you onPostExecute() becomes

// Executes in UI thread, after the execution of
// doInBackground()
@Override
protected void onPostExecute(ArrayList<String> results)
{
super.onPostExecute(results);

ParserTask parserTask = new ParserTask();

// Invokes the thread for parsing the JSON data
parserTask.execute(results);

}

Now, you will have to modify your ParserTask code to take in a list of JSON Strings, and not just one JSON String. Just change your ParserTask input parameters and put everything inside a for loop to loop through each JSON String. You will also have to modify the parameter of onPostExecute() to take in a List of whatever is there already, so that way it doesn't process one result, but a list of results. I can't show you those modifications here because it would be way too long, and then there would be no challenge for you :)

EDIT TWO: In getLastLocation() you're only calling DownloadTask with one URL, but you should put four URL's like this downloadTask.execute(url1, url2, url3, url4). Also, since ParserTask still only processes one JSON String, you should take out the four TextView's and the array looping out of the onPostExecute(). To tell the ParserTask which TextView to populate, add a constructor to ParserTask which takes in a TextView as a parameter. Then make an instance variable within ParserTaskthat is assigned in the constructor and used in onPostExecute() to display the distance.

Then, take that TextView array stuff I gave you before and put it in the onPostExecute() of DownloadTask. When you loop through the String results, also loop through the TextView array and pass in the TextView in the ParserTask constructor.

Basically, you're adding a constructor in the ParserTask to tell it which TextView to draw on. When your DownloadTask is finished, you pass it the right TextView for the URL. For example, R.id.location3 for the third URL.

Android: How to draw route directions google maps API V2 from current location to destination

This works great 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:

GMapV2Direction 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.

Getting Driving Directions and retrieving the JSON object using Google Maps API V2

Seems like your url is not providing an api key.
A sample API require URL should be like this: https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=API_KEY

Sample working code:

String API_KEY = "YOUR_API_KEY_STRING";
String input = "1600+Amphitheatre+Parkway,+Mountain+View,+CA";

private static boolean getAddressResult(String input, StringBuilder jsonResults) {
try {

URL requestUrl = new URL("https://maps.googleapis.com/maps/api/geocode/json?address=" + input " + &key=" + API_KEY;
);
HttpURLConnection connection = (HttpURLConnection)requestUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();


responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {

BufferedReader reader = null;

InputStream inputStream = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return false;
}
reader = new BufferedReader(new InputStreamReader(inputStream));

String line;
while ((line = reader.readLine()) != null) {
long elapsedTime = System.currentTimeMillis();
if(elapsedTime-currentTime>=5000) {
return false;
}
buffer.append(line + "\n");
}

if (buffer.length() == 0) {
return false;
}

Log.d("Test", buffer.toString());
return buffer.toString();
}
else {
Log.i(TAG, "Unsuccessful HTTP Response Code: " + responseCode);
return false
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return false;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return false;
} catch (Expcetion e) {
return false;
}
return false;
}

And please make sure you have to correct permissions (such as INTERNET) set up in your manifest file.
You can also make sure that internet on your device is actually connected.

Directions API for Android with traveling time

To draw path you can use this library

Through this library you can get travel duration between two point. now when you move to your destination location you have to calculate your speed and remaining destination distance. from your speed you can assume you destination reach time.

To calculate your moving speed this link will help you



Related Topics



Leave a reply



Submit