draw driving route on a fragment map with waypoints on android - android

I'm trying to draw a route on my fragmentMap; when i "give" to google only origin and destination points averythings goes fine; but when I try to add few waypoints, it fails!
This is the code, I hope you'll give me a solution, i'm going crazy!Thanks very much
String waypoints = "";
String wayp= "&waypoints=";
if(lp.size()>2){
for(int i=1;i<lp.size()-1;i++){
LatLng point = lp.get(i).getLoc();
waypoints += point.latitude + "," + point.longitude+ "|";
}
}else{
waypoints = "";
}
wayp +=waypoints;
Log.v("MAPPA", wayp);
String url = "http://maps.googleapis.com/maps/api/directions/xml?"
+ "origin=" + start.latitude + "," + start.longitude
+wayp+ "&destination=" + end.latitude + "," + end.longitude
+ "&sensor=false&units=metric&mode=driving";
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) {
Log.v("MAPPA", "CATCH");
e.printStackTrace();
}
Always in catch!

Related

"How to get the actual road distance between two places both the points are fixed"

We are creating an Android application and we need to calculate exact road distance between two fixed points. We require road distance not the Arial distance(Bird flying distance). We need to calculate the estimate trip cost before the trip starts.
Thanks in Advance.
All the answers and helps will be appreciated.
use goolge api
public float getDistance(double lat1, double lon1, double lat2, double lon2) {
String result_in_kms = "";
String url = "http://maps.google.com/maps/api/directions/xml?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric";
String tag[] = {"text"};
HttpResponse response = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
response = httpClient.execute(httpPost, localContext);
InputStream is = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(is);
if (doc != null) {
NodeList nl;
ArrayList args = new ArrayList();
for (String s : tag) {
nl = doc.getElementsByTagName(s);
if (nl.getLength() > 0) {
Node node = nl.item(nl.getLength() - 1);
args.add(node.getTextContent());
} else {
args.add(" - ");
}
}
result_in_kms =String.valueOf( args.get(0));
}
} catch (Exception e) {
e.printStackTrace();
}
Float f=Float.valueOf(result_in_kms);
return f*1000;
}
Here is a variation of the first answer. First call getDocument with start and end location, mode (driving, transit, cycling, walking), language. Then pass that document to getTurnByTurn(). This will return an array of 'steps' or legs of a trip, with a distance between the previous step's end point and the new step's end point. Might be in kilometers, need to convert to miles if necessary.
public Document getDocument(String start, String dest, String mode, String language) {
try {
start = URLEncoder.encode(start, "utf-8");
dest = URLEncoder.encode(dest, "utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
long milliseconds = System.currentTimeMillis();
long seconds = milliseconds/1000;
String url = "https://maps.googleapis.com/maps/api/directions/xml?departure_time="
+ seconds
+ "&origin=" + start
+ "&destination=" + dest
+ "&language=" + language
+ "&sensor=false&mode=" + mode;
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 ArrayList<SearchItem> getTurnByTurn (Document doc) {
NodeList nl1, nl2, nl3;
ArrayList<SearchItem> listDirections = new ArrayList<SearchItem>();
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 distanceNode = nl2.item(getNodeIndex(nl2, "distance"));
nl3 = distanceNode.getChildNodes();
Node textNode = nl3.item(getNodeIndex(nl3, "text"));
String distance = textNode.getTextContent();
Node durationNode = nl2.item(getNodeIndex(nl2, "duration"));
nl3 = durationNode.getChildNodes();
textNode = nl3.item(getNodeIndex(nl3, "text"));
String duration = textNode.getTextContent();
Node instructionsNode = nl2.item(getNodeIndex(nl2, "html_instructions"));
String instructions = instructionsNode.getTextContent();
String details = distance + " -- " + duration;
listDirections.add(new SearchItem(instructions, details, "", false));
}
}
return listDirections;
}

xamarin android googlemap directions

requestApi = "https://maps.googleapis.com/maps/api/directions/json?" + "mode=driving&" + "transit_routing_perference=less_driving&" + "origin=" + CurrentPostion.Latitude + "," + CurrentPostion.Longitude + "&" + "destination=" + Destionation + "&" + "key=AIzaSyCKxAGrqJaMBBXYMAI7gMvSJsjKrhA4_NQ ";
var address = "paris, france";
var requestUri = string.Format("https://maps.googleapis.com/maps/api/directions/json?mode=driving&transit_routing_perference=less_driving&origin='"+CurrentPostion.Latitude+"','"+CurrentPostion.Longitude+"'&destination='"+Destionation+"'&key=AIzaSyCKxAGrqJaMBBXYMAI7gMvSJsjKrhA4_NQ", Uri.EscapeDataString(address));
HttpClient client;
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
try
{
var response = await client.GetAsync(requestApi);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
Toast.MakeText(this, "result", ToastLength.Long).Show();
JSONObject jSONObject = new JSONObject(result);
JSONArray jSONArray = jSONObject.GetJSONArray("routes");
There is no jsonarry result what is wrong

google direction gives 0 values

hey I have used google direction to get duration it's working but sometime it return 0 value to json array routs. when I tested a day after return a value. is there any limitation for google direction request per day ?
and here is my function to get duration
public String getDistanceInfo(LatLng origin, LatLng dest) {
StringBuilder stringBuilder = new StringBuilder();
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
String dura = "";
try {
String sensor = "sensor=false";
String output = "json";
String mode = "mode=walking";
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;
// Output format
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
//String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + str_origin + "," + str_dest + "&destination=" + destinationAddress + "&mode=driving&sensor=false";
HttpPost httppost = new HttpPost(url);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
JSONArray array = jsonObject.getJSONArray("routes");
JSONObject routes = array.getJSONObject(0);
JSONArray legs = routes.getJSONArray("legs");
JSONObject steps = legs.getJSONObject(0);
JSONObject duration = steps.getJSONObject("duration");
dura = duration.getString("text");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dura;
}
org.json.JSONException: Index 0 out of range [0..0)
org.json.JSONArray.get(JSONArray.java:282)
org.json.JSONArray.getJSONObject(JSONArray.java:510)
Check to see if you are also getting something like this too in your JSON response apart from 0 for the duration.
{"status":"OVER_QUERY_LIMIT","routes":[]}.
This means that you are exceeding the limits of the Direction API usage. Please note that for standard version there are only 2,500 free directions requests per day available. If you need to request more, their are additional charges associated.
Check the official documentation on Google Maps Directions API Usage Limits more details.

Fetching Location Distance issue sending 0.0

I am using the following code the fetching the distance between difference latitude and longitude.Some time it works fine but some time it return the 0.0. I can't understand the reason why it happen. I have enable both GPS and Network
My code is..
public static String getDistanceOnRoad(String latitude, String longitude,
String prelatitute, String prelongitude) {
String result_in_kms = "";
float num_in_Km=0;
String url = "http://maps.google.com/maps/api/directions/xml?origin="
+ latitude + "," + longitude + "&destination=" + prelatitute
+ "," + prelongitude + "&sensor=false&units=metric";
String tag[] = { "text" };
HttpResponse response = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
response = httpClient.execute(httpPost, localContext);
InputStream is = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(is);
if (doc != null) {
NodeList nl;
ArrayList args = new ArrayList();
for (String s : tag) {
nl = doc.getElementsByTagName(s);
if (nl.getLength() > 0) {
Node node = nl.item(nl.getLength() - 1);
args.add(node.getTextContent());
} else {
args.add(" - ");
}
}
result_in_kms = String.format("%s", args.get(0));
//result come with 'm' and 'km' tag so remove this tag
String num=stripNonDigits(result_in_kms);
//if result in KM then does not devide by 1000
if(!isdisIn_M_or_KM(result_in_kms)){
num_in_Km=Float.valueOf(num)/1000;
}
else num_in_Km=Float.valueOf(num);
Log.i("", "");
}
} catch (Exception e) {
e.printStackTrace();
}
return String.valueOf(num_in_Km);
}
For Finding the distance using GPS, There is no Need of Network Connection. GPS will provide the Latitude and Longitude based on the the time interval you apply.
kindly refer the below link
Calculate distance between two latitude-longitude points? (Haversine formula)

How to get particular type of venue from list of venues, foursquare.

By using this code i got all venue details,here i want perticular type of venue lets say 'Hotels' ,'Restaurants' how to specify in the following code.
DefaultHttpClient httpclient = new DefaultHttpClient();
final HttpParams httpParams = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
HttpConnectionParams.setSoTimeout(httpParams, 30000);
HttpGet httppost = new HttpGet(
"https://api.foursquare.com/v2/venues/search?intent=checkin&ll="
+ lat + "," + longi + "&client_id=" + client_id
+ "&client_secret=" + client_secret + "&v="
+ 20131008); //
Tried this modified url to fox this issue.in url we can directly filter the venues.
try {
httppost = new HttpGet(
"https://api.foursquare.com/v2/venues/search?intent=checkin&ll="
+ lat + "," + longi + "&client_id=" + client_id
+ "&client_secret=" + client_secret +"&query="+ URLEncoder.encode("Hotel|Bar|Club|Cafe|CoffeeShops", "utf-8")+ "&v="
+ 20131008);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} //

Categories

Resources