How to make a multicolored overview polyline? - android

I have added an overview polyline in my map but now I want it look multicolored on different latitudes and longitudes.
If you can please help me find how to get through this problem I will be grateful
public void User(final Context context,final GoogleMap gMap) {
Log.d("seee",makeURL());
final MarkerOptions markerOptions=new MarkerOptions();
final StringRequest stringRequest = new StringRequest(Request.Method.POST, makeURL(), new Response.Listener<String>() {
List<LatLng> startLatLng=null;
#Override
public void onResponse(String response) {
JSONObject json=null;
try {
json = new JSONObject(response);
JSONArray routeArray = json.getJSONArray("routes");
for(int i=0;i<routeArray.length();i++) {
JSONObject routes = routeArray.getJSONObject(i);
JSONArray rAQI=routeArray.getJSONObject(i).getJSONArray("legs").getJSONObject(0).getJSONArray("steps");
startLatLng=getLatitudeLongitudes(rAQI);
JSONObject overviewPolylines = routes
.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = PolyUtil.decode(encodedString);
if(i!=0) {
PolylineOptions options = new PolylineOptions().width(17).color(ContextCompat.getColor(context,R.color.colorGreyline)).geodesic(true);
for (int z = 0; z < list.size(); z++) {
LatLng point = list.get(z);
options.add(point);
}
gMap.addPolyline(options);
options.clickable(true);
}
else {
PolylineOptions options = new PolylineOptions().width(20).color(ContextCompat.getColor(context,R.color.colorBlueline)).geodesic(true);
for (int z = 0; z < list.size(); z++) {
LatLng point = list.get(z);
options.add(point);
}
gMap.addPolyline(options);
options.clickable(true);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(context, ""+startLatLng.size(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "" + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(stringRequest);
}
I want to get something like this

Related

Getting marker details when marker is clicked

Hello i have this app that could detect users locations. In 1 activity I am displaying all the markers from mysql server using volley lirary and store in an array.
Now I want to get the data esp. the title of the marker and pass it to a String or a textview when it is clicked do something
here is my code:
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 20 seconds
if(locationsMarker != null){
locationsMarker.remove();
}
StringRequest stringRequest2 = new StringRequest(Request.Method.GET, locs_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array= new JSONArray(response);
JSONObject locations;
String from_lat_lng="";
for (int i = 0; i < array.length(); i++) {
locations = new JSONObject(array.get(i).toString());
String locs = locations.getString("current_loc");
Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(locs);
while(m.find()) {
from_lat_lng = m.group(1) ;
}
String[] gpsVal = from_lat_lng.split(",");
double lat = Double.parseDouble(gpsVal[0]);
double lon = Double.parseDouble(gpsVal[1]);
LatLng location_array = new LatLng(lat,lon);
Toast.makeText(ScanToHelp.this, "haha="+location_array.toString(), Toast.LENGTH_LONG).show();
points.add(location_array); //added
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(location_array);
markerOptions.title("Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
locationsMarker = mMap.addMarker(markerOptions);
// mMap.moveCamera(CameraUpdateFactory.newLatLng(location_array));
// mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(location_array, 17.2f));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
MySingleton.getInstance(ScanToHelp.this).addToRequestQueue(stringRequest2);
handler.postDelayed(this, 3000);
}
}, 100); //the time is in miliseconds
Thanks,

Add marker to map from JSON, Android

I was trying to add markers to a map automatically after getting the data from JSON, with the position that is in the api, this is what I have:
#Override
protected Void doInBackground(Void... params) {
HttpHandler sh2 = new HttpHandler();
final String jsonStrOportunidades = sh2.makeServiceCall(urlOportunidades);
Log.e(TAG, "Response from URL: " + jsonStrOportunidades);
if (jsonStrOportunidades != null) {
try {
JSONArray array = new JSONArray(jsonStrOportunidades);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String Designacao = jsonObject.getString("Designacao");
String Coord_LAT = jsonObject.getString("Coord_LAT");
String Coord_LONG = jsonObject.getString("Coord_LONG");
HashMap<String, String> oportunidades = new HashMap<>();
oportunidades.put("Designacao", Designacao);
oportunidades.put("Coord_LAT", Coord_LAT);
oportunidades.put("Coord_LONG", Coord_LONG);
double lat1 = Double.parseDouble(Coord_LAT);
double lng1 = Double.parseDouble(Coord_LONG);
mMap.addMarker(new MarkerOptions().position(new LatLng(lat1, lng1)));
listaOportunidades.add(oportunidades);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsin error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
return null;
}
"mMap.addMarker" doesn't work, is it even possible creating markers from there?
Try setting the marker from onPostExecute. doInBackground isn't the place to update UI components.
#Override
protected String doInBackground(Void... params) {
HttpHandler sh2 = new HttpHandler();
final String jsonStrOportunidades = sh2.makeServiceCall(urlOportunidades);
Log.e(TAG, "Response from URL: " + jsonStrOportunidades);
return jsonStrOportunidades;
}
#Override
protected void onPostExecute(String jsonStrOportunidades){
if (jsonStrOportunidades != null) {
try {
JSONArray array = new JSONArray(jsonStrOportunidades);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String Designacao = jsonObject.getString("Designacao");
String Coord_LAT = jsonObject.getString("Coord_LAT");
String Coord_LONG = jsonObject.getString("Coord_LONG");
HashMap<String, String> oportunidades = new HashMap<>();
oportunidades.put("Designacao", Designacao);
oportunidades.put("Coord_LAT", Coord_LAT);
oportunidades.put("Coord_LONG", Coord_LONG);
double lat1 = Double.parseDouble(Coord_LAT);
double lng1 = Double.parseDouble(Coord_LONG);
mMap.addMarker(new MarkerOptions().position(new LatLng(lat1, lng1)));
listaOportunidades.add(oportunidades);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
Toast.makeText(getApplicationContext(), "Json parsin error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
Also, you need to change the AsyncTask class like this
YourAsyncTaskClass extends AsyncTask<String, Void, String>

Unable to get value of arrayList inside the getView() method of Adapter Class

This is my getView() method where I am trying to set the values of distance after fetching from the volley .Here distance calculation is proper.
public View getView(final int position, View convertView, ViewGroup parent)
{
listrowposition = position;
if (convertView == null)
{
LayoutInflater inflater = getActivity().getLayoutInflater();
convertView = inflater.inflate(R.layout.singlerowallassigendloction, null);
holder = new ViewHolder();
holder.distance = (TextView) convertView.findViewById(R.id.distance);
holder.lati = (TextView) convertView.findViewById(R.id.lati);
holder.longi = (TextView) convertView.findViewById(R.id.longi);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.lati.setText(salesmanlocationArrayList.get(listrowposition).getLati());
holder.longi.setText(salesmanlocationArrayList.get(listrowposition).getLongi());
double lat1= Double.parseDouble(holder.lati.getText().toString());
double lng1= Double.parseDouble(holder.longi.getText().toString());
vollyRequest_Fetch_distance(lat1,lng1,lat,lng);
Log.d("distance_ll=","tex="+text+" "+value+" "+lat1);
double d= Double.parseDouble(value)/1000;
holder.distance.setText(""+new DecimalFormat("##.##").format(d)+" KM");
return convertView;
}
This is my volley request code
public void vollyRequest_Fetch_distance(double lat11, double lon11, double lat22, double lon22)
{
String url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins="+lat11+","+lon11+"&"+"destinations="+lat22+","+lon22;
Log.d("RESPOetchlocation..>>> ", url + "<<<");
RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
Log.d("RESPONFetchlocation>>> ", response + "<<<");
// progressDialog.dismiss();
Jsonresponse_Distance(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("RESPONSE:Error>>> ", error.toString() + "<<<");
// progressDialog.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("key", "Arz5SyA5UFy-pTsr5cIdwxghhnV6BoH-pCJBARg");
return params;
}
};
queue.add(request);
}
public void Jsonresponse_Distance(String str)
{
JSONObject jsonObject = null;
JSONArray jsonArray = null;
JSONArray jsonArray_elements = null;
JSONObject jsonObject_elements = null;
JSONObject jobj;
String error = null;
String msg = null;
try
{
jsonObject = new JSONObject(str);
Log.d("jsonObject==", jsonObject.toString());
msg = jsonObject.getString("status");
if (msg.equals("OK"))
{
jsonArray = jsonObject.getJSONArray("rows");
Log.d("jsonArray.length()=",""+jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++)
{
jobj= jsonArray.getJSONObject(i);
jsonArray_elements= jobj.getJSONArray("elements");
Log.d("jsonArray_ets.length()=",""+jsonArray_elements.length());
for (int j = 0; j < jsonArray_elements.length(); j++)
{
jsonObject_elements= jsonArray_elements.getJSONObject(0);
Log.d("jsonObject_elements=",jsonObject_elements.toString());
JSONObject job= jsonObject_elements.getJSONObject("distance");
Log.d("job=",job.toString());
text= job.getString("text");
value= job.getString("value");
Log.d("job=",""+text+" "+value);
}
}
}
else
{
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
I am getting proper result for value (distance ) but getting null inside getview method please help me out.
// Here I am trying to set my adapter after fetching volley request
public void Jsonresponse_Viewlocation(String str)
{
JSONObject jsonObject = null;
JSONArray jsonArray = null;
JSONObject jobj;
String error = null;
String msg = null;
salesmanlocationArrayList.clear();
try
{
jsonObject = new JSONObject(str);
Log.d("jsonObject==", jsonObject.toString());
msg = jsonObject.getString("status");
if (msg.equals("true")) {
jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++)
{
salesmanlocation = new Salesmanlocation();
jobj = jsonArray.getJSONObject(i);
address = jobj.getString("address");
salesmanlocation.setAddress(address); salesmanlocation.setAddress(jobj.getString("address"));
String latlong_string=getLocationFromAddress(address);
String latlong[]=latlong_string.split(",");
String lat1=latlong[0];
String lng1=latlong[1];
Log.d("latlng==",""+lat1+" "+lng1);
double latt= Double.parseDouble(lat1);
double lng1g= Double.parseDouble(lng1);
salesmanlocation.setLati(String.valueOf(lat1));
salesmanlocation.setLongi(String.valueOf(lng1));
salesmanlocationArrayList.add(salesmanlocation);
}
}
else
{
}
}
catch (JSONException e)
{
e.printStackTrace();
}
adapter = new Baseddapter_Allassignloc();
alllist.setAdapter(adapter);
}

Displaying markers in a certain radius in Android

I am making an app that uses maps api. I have a bunch of markers on the server. What I want to do is display only the markers in the certain radius of user's current location (for example, show all markers in a 10 kilometer radius from my current location).
MapFragment:
if (myLocation != null) {
latitude = myLocation.getLatitude();
longitude = myLocation.getLongitude();
}
MarkerOptions markerOptions = new MarkerOptions().position(
new LatLng(latitude, longitude)).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_me));
mMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)).zoom(12).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(final LatLng arg0) {
RequestQueue queue = Volley.newRequestQueue(getActivity());
String url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + String.valueOf(arg0.latitude) + "," + String.valueOf(arg0.longitude) + "&key=myKey";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jObj = new JSONObject(response).getJSONArray("results").getJSONObject(0).getJSONArray("address_components");
Intent intent = new Intent(getActivity(), SetRestaurantActivity.class);
for (int i = 0; i < jObj.length(); i++) {
String componentName = new JSONObject(jObj.getString(i)).getJSONArray("types").getString(0);
if (componentName.equals("postal_code") || componentName.equals("locality") || componentName.equals("street_number") || componentName.equals("route")
|| componentName.equals("neighborhood") || componentName.equals("sublocality") || componentName.equals("administrative_area_level_2")
|| componentName.equals("administrative_area_level_1") || componentName.equals("country")) {
intent.putExtra(componentName, new JSONObject(jObj.getString(i)).getString("short_name"));
}
}
intent.putExtra("latitude", arg0.latitude);
intent.putExtra("longitude", arg0.longitude);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
int x = 1;
}
});
queue.add(stringRequest);
}
});
MyRestaurantsFragment:
public class RestaurantsFragment extends Fragment {
private static final String TAG = RestaurantsFragment.class.getSimpleName();
// Restaurants json url
private ProgressDialog pDialog;
private List<Restaurant> restaurantList = new ArrayList<>();
private ListView listView;
private CustomListAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_restaurants, container, false);
listView = (ListView) view.findViewById(R.id.restaurants_list);
adapter = new CustomListAdapter(getActivity(), restaurantList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();
SQLiteHandler db = new SQLiteHandler(getActivity().getApplicationContext());
HashMap<String, String> user = db.getUserDetails();
final String userId = user.get("uid");
StringRequest restaurantReq = new StringRequest(Request.Method.POST,
AppConfig.URL_GET_RESTAURANT, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
JSONArray restaurants = jObj.getJSONArray("restaurant");
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < restaurants.length(); i++) {
try {
JSONObject obj = restaurants.getJSONObject(i);
Restaurant restaurant = new Restaurant();
restaurant.setUserName(obj.getString("name"));
if (obj.getString("image") != null && !obj.getString("image").isEmpty()) {
restaurant.setThumbnailUrl(obj.getString("image"));
}
restaurant.setLat(obj.getString("latitude"));
restaurant.setLon(obj.getString("longitude"));
restaurant.setDate(obj.getString("restaurant_name"));
restaurant.setTime(obj.getString("restaurant_description"));
// adding restaurant to restaurant array
restaurantList.add(restaurant);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
} else {
// Error. Get the error message
String errorMsg = jObj.getString("error_msg");
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
},
Use SphericalUtils method computeDistanceBetween() from google-maps-utils to calculate distance from your position to every restaurant and filter out its collection by calculated distance
...
restaurant.setDate(obj.getString("restaurant_name"));
restaurant.setTime(obj.getString("restaurant_description"));
restaurant.setLat(obj.getString("latitude"));
restaurant.setLon(obj.getString("longitude"));
// adding restaurant to restaurant array
if (SphericalUtil.computeDistanceBetween(new LatLng(restaurant.getLat(), restaurant.getLon()), userLatLng)<10)
restaurantList.add(restaurant);
}

android json data retrieving

I am new to Json. I want to retrieve the distance between two places using json. I want to get "text"(Distance b/w two places) from "distance" object which is in "legs" array which in turn is in "routes" array.
Link(http://maps.googleapis.com/maps/api/directions/json?origin=Adoor&destination=Thiruvananthapuram%20Zoo&sensor=false)
Java code:
String uri="http://maps.googleapis.com/maps/api/directions/json?origin="+destination+"&destination="+tour_place+"&sensor=false";
queue= Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest objectRequest=new JsonObjectRequest(Request.Method.GET, uri, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array=response.getJSONArray("legs");
distances.add(array.getJSONObject(0).getJSONObject("distance").getDouble("text"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error){
}
});
queue.add(objectRequest);
Okay, will now post the code I did. Try this out.
try {
JSONObject json = new JSONObject(jStr);
JSONArray jaRoutes = json.getJSONArray("routes");
JSONArray jaLegs = jaRoutes.getJSONObject(0).getJSONArray("legs");
JSONObject joDistance = jaLegs.getJSONObject(0).getJSONObject("distance");
String text = joDistance.getString("text");
Toast.makeText(this, text, Toast.LENGTH_SHORT);
} catch (JSONException e) {
Log.d("SAMPLE", e.toString());
}
Let me know if it works.
Try this,
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
JSONObject jDistance = null;
JSONObject jDuration = 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<HashMap<String, String>> 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("text"));
/** Getting duration from the json data */
jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
HashMap<String, String> hmDuration = new HashMap<String, String>();
hmDuration.put("duration", jDuration.getString("text"));
/** Adding distance object to the path */
path.add(hmDistance);
/** Adding duration object to the path */
path.add(hmDuration);
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** 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){
}
Try code below:
try {
StringRequest sr = new StringRequest(Request.Method.GET, uri, (String) null, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.dismiss();
;
Log.d("", ".......response====" + response.toString());
////////
try {
JSONObject object = new JSONObject(response);
if (serverCode.equalsIgnoreCase("0")) {
}
if (serverCode.equalsIgnoreCase("1")) {
try {
if ("1".equals(serverCode))
{
JSONArray jsonArray = object.getJSONArray("routes");
if(jsonArray.length()>0)
{
for(int i=0; i<jsonArray.length(); i++)
{
JSONArray legs =jsonArray.getJSONArray("legs");
if(legs.length()>0)
{
for(int i=0; i<legs.length(); i++)
{
JSONObject object1 = legs.getJSONObject("distance");
String distance = object1.getString("text");
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
;
// VolleyLog.d("", "Error: " + error.getMessage());
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Toast.makeText(ForgotPasswordActivity.this, "Timeout Error",
Toast.LENGTH_LONG).show();
} else if (error instanceof AuthFailureError) {
VolleyLog.d("", "" + error.getMessage() + "," + error.toString());
} else if (error instanceof ServerError) {
VolleyLog.d("", "" + error.getMessage() + "," + error.toString());
} else if (error instanceof NetworkError) {
VolleyLog.d("", "" + error.getMessage() + "," + error.toString());
} else if (error instanceof ParseError) {
VolleyLog.d("", "" + error.getMessage() + "," + error.toString());
}
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_email", email);
return params;
}
};
sr.setShouldCache(true);
sr.setRetryPolicy(new DefaultRetryPolicy(50000 * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(sr);
} catch (Exception e) {
e.printStackTrace();
}
Try this
try{
JSONObject object = new JSONObject(thewholething.toString());
JSONArray routes =object.getJSONArray("routes");
JSONArray legs=routes.getJSONObject(0).getJSONArray("legs")
JSONObject distance =legs.getJSONObject(0).getJSONObject("distance");
String text=distance.getString("text");
}
catch (JSONException e) {
e.printStackTrace();
}
Now the String text contains your value.
From your response, you parse your routes array first.
JsonArray routes = response.getJsonArray("routes");
From here, you can get legs array like the following.
JsonArray legs = routes.getJsonArray("legs");

Categories

Resources