Маршруты не всегда отображаются на картах api android - PullRequest
0 голосов
/ 29 октября 2019

Я застрял в очень утомленной проблеме. Ниже мой код, чтобы получить маршрут и отобразить его на карте. Это так же, как и любой другой пример.

        String phase1lt = "30.717578";
        String phase1lng = "76.713802";
        String phase7lat = "30.719133";
        String phase7lng = "76.7109453";
        new GoogleMapsPath(getActivity(),mMap,new LatLng(Double.parseDouble(phase1lt),Double.parseDouble(phase1lng)),
                new LatLng(Double.parseDouble(phase7lat),Double.parseDouble(phase7lng)));

Ниже приведен выбор классов и обработка каждой вещи.

public class GoogleMapsPath {

public GoogleMap map;
Context context;

public GoogleMapsPath(Context context, GoogleMap map, LatLng origin, LatLng dest){
    this.map = map;
    this.context = context;

    map.clear();
    String url = getDirectionsUrl(origin,dest);
    Log.e("url is called","+++++"+url);
    FetchUrl FetchUrl = new FetchUrl();
    FetchUrl.execute(url);

}

// Fetches data from url passed
private class FetchUrl extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... url) {

        // For storing data from web service
        String data = "";

        try {
            // Fetching the data from web service
            data = downloadUrl(url[0]);
            Log.e("Background Task data", data.toString());
        } catch (Exception e) {
            Log.e("Background Task", e.toString());
        }
        return data;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        ParserTask parserTask = new ParserTask();

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

    }
}


private String downloadUrl(String strUrl) throws IOException {
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(strUrl);

        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

        StringBuffer sb = new StringBuffer();

        String line = "";
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        data = sb.toString();
        Log.d("downloadUrl", data.toString());
        br.close();

    } catch (Exception e) {
        Log.d("Exception", e.toString());
    } finally {
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}


private String getDirectionsUrl(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";

    String mode = "mode=driving";

    // Building the parameters to the web service
    String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;

    // Output format
    String output = "json";


    String API_KEY = "AIzaSyAHMVR4NFKFVFL7Bf71rGykJi0e0OpIPLg";

    // Building the url to the web service
    String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters + "&key=" + API_KEY;

    return url;
}


private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {

    // Parsing the data in non-ui thread
    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {

        JSONObject jObject;
        List<List<HashMap<String, String>>> routes = null;

        try {
            jObject = new JSONObject(jsonData[0]);
            Log.d("ParserTask",jsonData[0].toString());
            DirectionsJSONParser parser = new DirectionsJSONParser();
            Log.d("ParserTask", parser.toString());

            // Starts parsing data
            routes = parser.parse(jObject);
            Log.d("ParserTask","Executing routes");
            Log.d("ParserTask",routes.toString());

        } catch (Exception e) {
            Log.d("ParserTask",e.toString());
            e.printStackTrace();
        }
        return routes;
    }

    // Executes in UI thread, after the parsing process
    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        ArrayList<LatLng> points;
        PolylineOptions lineOptions = null;
        points = new ArrayList<>();
        // 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);

            // Fetching all the points in i-th route
            for (int j = 0; j < path.size(); j++) {
                HashMap<String, String> point = path.get(j);

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);
                Log.e("------lat","--lat--"+lat);
                Log.e("------lng","--lng--"+lng);

                points.add(position);
            }


            Log.d("onPostExecute","onPostExecute lineoptions decoded");

        }
        lineOptions = new PolylineOptions();
        // Adding all the points in the route to LineOptions
        lineOptions.addAll(points);
        lineOptions.width(8);
        lineOptions.color(context.getResources().getColor(R.color.bark_blue));
        lineOptions.geodesic(true);

        // Drawing polyline in the Google Map for the i-th route
        if(lineOptions != null) {
            map.addPolyline(lineOptions);
        }
        else {
            Log.d("onPostExecute","without Polylines drawn");
        }
    }
}

Я могу отобразить маршрут с указанным выше началом иназначение широтаНо когда я пытаюсь передать текущее местоположение водителя и пользователя и место получения, маршрут не отображается. Мне интересно, как другие способны отображать. Еще одна вещь, чтобы сказать. Я в состоянии получить каждый путь маршрута JSON Respose, но некоторые, как его не отображается на карте.

...