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.
Related
The below code is getting response code 401.please help anyone to get search tweets from twitter api.I am using http urlconnection instead of httprequest.I need to get response tweets using jsonobject
HttpURLConnection urlConnection=null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.twitterlayout);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
twitter_consumer_key= "";
twitter_consumer_secret="";
oauth_token = "";
oauth_token_secret = "";
q="India";
String get_or_post = "GET";
// This is the signature method used for all Twitter API calls
String oauth_signature_method = "HMAC-SHA1";
// generate any fairly random alphanumeric string as the "nonce". Nonce = Number used ONCE.
String uuid_string = UUID.randomUUID().toString();
uuid_string = uuid_string.replaceAll("-", "");
String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here
// get the timestamp
Calendar tempcal = Calendar.getInstance();
long ts = tempcal.getTimeInMillis();// get current time in milliseconds
String oauth_timestamp = (new Long(ts/1000)).toString(); // then divide by 1000 to get seconds
// assemble the proper parameter string, which must be in alphabetical order, using your consumer key
String parameter_string = "lang=en&oauth_consumer_key=" + twitter_consumer_key + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method +
"&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + URLEncoder.encode(oauth_token) + "&oauth_version=1.0&q=" + URLEncoder.encode(q) + "&result_type=mixed";`enter code here`
enter code here
Log.d("parameter_string=",parameter_string);
twitter_endpoint = "https://api.twitter.com/1.1/users/search.json";
twitter_url="https://api.twitter.com/1.1/users/search.json?q=india";
String signature_base_string = get_or_post + "&"+ URLEncoder.encode(twitter_endpoint) + "&" + URLEncoder.encode(parameter_string);
String oauth_signature = "";
try {
oauth_signature = computeSignature(signature_base_string, twitter_consumer_secret + "&");
}
catch (GeneralSecurityException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String authorization_header_string = "OAuth oauth_consumer_key=\"" + twitter_consumer_key + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp +
"\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + URLEncoder.encode(oauth_signature) + "\",oauth_token=\"" + URLEncoder.encode(oauth_token) + "\"";
Log.d("Header String",authorization_header_string);
URL url = null;
try
{
Log.d("Url",twitter_url);
url = new URL(twitter_url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Host", "api.twitter.com");
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
urlConnection.setRequestProperty("Authorization",authorization_header_string);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setUseCaches(false);
int responseCode = urlConnection.getResponseCode();
Log.d("Response Code :", String.valueOf(responseCode));
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String responsedata = null;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject topLevel = new JSONObject(jsonCallbackToJson(builder.toString()));
Log.d("Toplevel", builder.toString());
}
catch (MalformedURLException e) {
e.printStackTrace();
Log.i("URL-ERROR:",e.toString());
}
catch (IOException | JSONException e)
{
e.printStackTrace();
Log.i("IO-ERROR:", e.toString());
}
}
401 means you have broke something with authentication
However, don't reinvent the wheel.
You can use TwitterCore Kit that handle authentication and is easy to use tool for your needs. It provides a TwitterApiClient for making authenticated Twitter API requests.
I’m new with android studio. I want to use Volley to retrieve data from the Google server. I use two HTTP URL to search for nearby places and the distance and time from current location. However, I cannot find any method to use Volley for sending two “JSONRequest”. First request for searching nearby places and the second one for distance and time matrix for each nearby places from current location. The distance matrix HTTP URL is depend on the first one to find the nearby places before it can be executed. Is there any method to search nearby places with distance and time using single HTTP URL?
Or other method to use Volley for multiple request?
Your help is appreciated.
Here the Code I'm Using:
private int PROXIMITY_RADIUS = 5000; //5.0KM
private String NAME = "emergency";// emergency+hospital
private String TYPE = "hospital";
private String googlePlacesData;
private String googleDistData;
private Places placeJsonParser = new Places();
public List<PlaceData> searchNearby(double latitude, double longitude)
throws Exception{
List<PlaceData> googlePlacesList = new ArrayList<>();
try {
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=" + latitude + "," + longitude);
//googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
googlePlacesUrl.append("&rankby=distance");
googlePlacesUrl.append("&name=" + NAME);
googlePlacesUrl.append("&type=" + TYPE);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + GOOGLE_API_KEY);
if (googlePlacesUrl.length() > 0)
System.out.println("Exist GooglePlacesURL: " + googlePlacesUrl.toString());
Http http = new Http();
googlePlacesData = http.read(googlePlacesUrl.toString());
googlePlacesList = placeJsonParser.parse(new JSONObject(googlePlacesData));
}catch (Exception e){
e.printStackTrace();
}
return googlePlacesList;
}
public List<PlaceData> distanceMatrix(List<PlaceData> googlePlace,GPSTracker gps){
List<PlaceData> googlePlacesDistTimeList = new ArrayList<>();
try {
StringBuilder googleDistTimeURL = new StringBuilder("https://maps.googleapis.com/maps/api/distancematrix/json?");
googleDistTimeURL.append("origins=" + gps.getLatitude() + "," + gps.getLongitude());
googleDistTimeURL.append("&destinations=");
int counter = 0;
for (PlaceData place:googlePlace){
if (counter != (googlePlace.size()-1)){
googleDistTimeURL.append(place.getLatitude() + "," + place.getLongitude() + "|");
}else {
googleDistTimeURL.append(place.getLatitude() + "," + place.getLongitude());
}
counter++;
}
googleDistTimeURL.append("&key=" + GOOGLE_API_KEY);
if (googleDistTimeURL.length() > 0)
System.out.println("Exist GooglePlacesURL: " + googleDistTimeURL.toString());
Http http = new Http();
googleDistData = http.read(googleDistTimeURL.toString());
googlePlacesDistTimeList = placeJsonParser.parseDistTime(new JSONObject(googleDistData),googlePlace);
}catch (Exception e){
Log.e("Exception", e.toString());
}
return googlePlacesDistTimeList;
}
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)
I want to find out driving distance between two latitude and longitude.
this is my code
private String GetDistance(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 urlString = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + parameters;
// get the JSON And parse it to get the directions data.
HttpURLConnection urlConnection = null;
URL url = null;
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
InputStream inStream = urlConnection.getInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(
inStream));
String temp,response = "";
while ((temp = bReader.readLine()) != null) {
// Parse data
response += temp;
}
// Close the reader, stream & connection
bReader.close();
inStream.close();
urlConnection.disconnect();
// Sort out JSONresponse
// JSONObject object = (JSONObject) new JSONTokener(response)
// .nextValue();
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("routes");
// Log.d("JSON","array: "+array.toString());
// Routes is a combination of objects and arrays
JSONObject routes = array.getJSONObject(0);
// Log.d("JSON","routes: "+routes.toString());
String summary = routes.getString("summary");
Log.d("JSON","summary: "+summary);
JSONArray legs = routes.getJSONArray("legs");
// Log.d("JSON","legs: "+legs.toString());
JSONObject steps = legs.getJSONObject(0);
// Log.d("JSON","steps: "+steps.toString());
JSONObject distance = steps.getJSONObject("distance");
// Log.d("JSON","distance: "+distance.toString());
sDistance = distance.getString("text");
iDistance = distance.getInt("value");
} catch (Exception e) {
// TODO: handle exception
return e.toString();
}
return sDistance;
}
and i am getting a exception
org.json.JSONException:Index 0 out of range [0..0)
this is my stacktrace
Ljava.lang.StackTraceElement;#41019be8
please help me out what is the problem.
First of all, don't hardcode any position(like 0) to get from array. Bcs, the array may be empty.
That's what happened in your case. One of your array or legs JSONArray is empty but you are trying to get the 0th position of them. So,it is throwing index out of range exception.
To get the values from an array better use for loop. An example code snippet is:
Log.v("array-length--", ""+array.length());
for(int i=0; i < array.length();i++)
{
// Routes is a combination of objects and arrays
JSONObject routes = array.getJSONObject(i);
// Log.d("JSON","routes: "+routes.toString());
String summary = routes.getString("summary");
Log.d("JSON","summary: "+summary);
JSONArray legs = routes.getJSONArray("legs");
// Log.d("JSON","legs: "+legs.toString());
Log.v("legs-length--", ""+legs.length());
for(int j=0; j < legs.length(); j++)
{
JSONObject steps = legs.getJSONObject(j);
// Log.d("JSON","steps: "+steps.toString());
JSONObject distance = steps.getJSONObject("distance");
// Log.d("JSON","distance: "+distance.toString());
sDistance = distance.getString("text");
iDistance = distance.getInt("value");
}
}
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!