0

I'm trying to implement a functionality in my app which uses the Google Maps API Directions to draw a path (from A to B) in the map. For some reason it seems that the application can't even make the request. It always takes the case of result.size()<1

 protected void onPostExecute(List<List<HashMap<String, String>>> result) {
             ArrayList<LatLng> points = null;
             PolylineOptions lineOptions = null;
             MarkerOptions markerOptions = new MarkerOptions();
             String distance = "";
             String duration = "";
             dialogz.dismiss();
             if(result.size()<1){
                 Toast.makeText(getBaseContext(), "Road name cannot be identified, Please choose a nearest location", Toast.LENGTH_SHORT).show();
                 return;
             }

             for(int i=0;i<result.size();i++){
                 points = new ArrayList<LatLng>();
                 lineOptions = new PolylineOptions();
                 List<HashMap<String, String>> path = result.get(i);
                 for(int j=0;j<path.size();j++){
                     HashMap<String,String> point = path.get(j);
                     if(j==0){
                         distance = (String)point.get("distance");
                         continue;
                     }else if(j==1){
                         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);

                     points.add(position);
                 }

                 // Adding all the points in the  route to LineOptions
                 lineOptions.addAll(points);
                 lineOptions.width(18);
                 lineOptions.color(Color.parseColor("#2E2E2E"));

             }
---and this is the code of getDirectionUrl----

 private void getDirectionsUrl(LatLng picklatlng,LatLng droplatlng){
         if(picklatlng!=null && droplatlng!=null) {
             String str_origin = "origin=" + picklatlng.latitude + "," + picklatlng.longitude;
             String str_dest = "destination=" + droplatlng.latitude + "," + droplatlng.longitude;
             String sensor = "sensor=false";
             String parameters = str_origin + "&" + str_dest + "&" + sensor;
             String output = "json";
             String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
             DownloadTask downloadTask = new DownloadTask();
             downloadTask.execute(url);
         }
     }
evan
  • 5,443
  • 2
  • 11
  • 20
alpha88
  • 9
  • 2

1 Answers1

0

Your code looks fine, except I don't see you're adding an API key to the Directions API request.

Make sure you add a (unrestricted) one, which cannot be the same one you use to load your Google map (assuming that API key is Android restricted - which it should be). To learn how to secure it please check out related thread How to use Google-Directions-Android library with a restricted API key

This is the working code I used.

import android.os.Bundle;

import androidx.fragment.app.FragmentActivity;

import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.maps.model.LatLng;

import org.json.JSONObject;

public class MapsActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        getDirectionsUrl(new LatLng(35.1, -117.9), new LatLng(37.7, -122.4));
    }

    private void getDirectionsUrl(LatLng picklatlng, LatLng droplatlng) {
        if (picklatlng != null && droplatlng != null) {
            String str_origin = "origin=" + picklatlng.latitude + "," + picklatlng.longitude;
            String str_dest = "destination=" + droplatlng.latitude + "," + droplatlng.longitude;
            String sensor = "sensor=false";
            String parameters = str_origin + "&" + str_dest + "&" + sensor;
            String output = "json";
            String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?key=MY_API_KEY&" + parameters;

            JsonObjectRequest jsonRequest = new JsonObjectRequest
                    (Request.Method.GET, url, null, new com.android.volley.Response.Listener // CHANGES HERE
                            <JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            System.out.println(response.toString());
                        }
                    }, new com.android.volley.Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError error) {
                            error.printStackTrace();
                        }
                    });
            Volley.newRequestQueue(this).add(jsonRequest);
        }
    }
}

Output:

{"geocoded_waypoints":[{"geocoder_status":"OK","place_id":"ChIJm_nMTZjSw4ARZA1AAEnxllA","types":["route"]},{"geocoder_status":"OK","place_id":"Eic3MDMgVHVubmVsIEF2ZSwgQnJpc2JhbmUsIENBIDk0MDA1LCBVU0EiGxIZChQKEglzvTxD1niPgBGTzG36JaRIkxC_BQ","types":["street_address"]}],"routes":[{"bounds":{"northeast":{"lat":37.6999852,"lng":-117.9000042},"southwest":{"lat":35.097047,"lng":-122.4068915}},"copyrights":"Map data ©2020 Google","legs":[{"distance":{"text":"355 mi","value":572013},"duration":{"text":"5 hours 41 mins","value":20477},"end_address":"703 Tunnel Ave, Brisbane, CA 94005, USA","end_location":{"lat":37.6999852,"lng":-122.4003035},"start_address":"Georgia Ave, Edwards, CA 93523, USA","start_location":{"lat":35.1006073,"lng":-117.9000042},"steps":[{"distance":{"text":"285 ft","value":87},"duration":{"text":"1 min","value":7},"end_location":{"lat":35.100593,"lng":-117.900961}, [...]

Hope this helps!

evan
  • 5,443
  • 2
  • 11
  • 20