Рисование линии между точкой обратного геокодирования и текущим местоположением - PullRequest
0 голосов
/ 28 февраля 2019

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

Код обратного геокодера:

  if (Geocoder.isPresent()) {
        try {
            String location = userLocation;
            Geocoder gc = new Geocoder(this);
            // get the found Address Objects
            List<Address> addresses = gc.getFromLocationName(location, 5);
            for (Address a : addresses) {
                if (a.hasLatitude() && a.hasLongitude()) {
                    mLat = a.getLatitude();
                    mLon = a.getLongitude();
                }
            }
        } catch (IOException e) {
            Log.d("eeee", e.toString());
        }

    }

Для моего текущего местоположения я реализовал прослушиватель местоположения и переопределил метод onLocationChanged, чтобы получить мое текущее местоположение.

Остальная частьлогика:

 @Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    LatLng myLocation = new LatLng(lat, lon);
    mMap.addMarker(new MarkerOptions().position(myLocation).title("Current Location"));
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLocation, 16));


    LatLng point = new LatLng(mLat, mLon);
    // check if there are already two locations
    if (markerPoints.size() > 1) {
        markerPoints.clear();
        mMap.clear();
    }
    // Adding new item to the ArrayList
    markerPoints.add(point);

    // Creating MarkerOptions
    MarkerOptions options = new MarkerOptions();

    // Setting the position of the marker
    options.position(point);

            /*
              For the start location, the color of marker is GREEN and
              for the end location, the color of marker is RED.
             */
    if (markerPoints.size() == 1) {
        options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
    } else if (markerPoints.size() == 2) {
        options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
    }

    // Add new marker to the Google Map
    mMap.addMarker(options);

    // Checks, whether start and end locations are captured
    if (markerPoints.size() >= 2) {
        LatLng origin = (LatLng) markerPoints.get(0);
        LatLng dest = (LatLng) markerPoints.get(1);

        // Getting URL to the Google Directions API
        String url = this.getUrl(origin, dest);


        FetchUrl FetchUrl = new FetchUrl();
        // Start downloading json data from Google Directions API
        FetchUrl.execute(url);

        //move map camera
        mMap.moveCamera(CameraUpdateFactory.newLatLng(origin));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
    }
}


private String getUrl(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 + "&" +
    getResources().getString(R.string.google_maps_key);

    // Output format
    String output = "json";

    // Building the url to the web service
    return "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
}


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]);

        } catch (Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        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));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        data = sb.toString();
        br.close();
    } catch (Exception e) {
        Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
    } finally {
        if (iStream != null) {
            iStream.close();
        }
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    return data;
}

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


    @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]);

            DataParser parser = new DataParser();


            // Starts to parse the data
            routes = parser.parse(jObject);

        } catch (Exception e) {
            Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
            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;
        // Traversing through all the routes
        for (int i = 0; i < result.size(); i++) {
            points = new ArrayList<>();
            lineOptions = new PolylineOptions();
            // 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);
                points.add(position);
            }
            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(10);
            lineOptions.color(Color.RED);

        }
        // Drawing polyline in the Google Map for the i-th route
        if (lineOptions != null) {
            mMap.addPolyline(lineOptions);
        } else {
            Toast.makeText(this, "null", Toast.LENGTH_SHORT).show();
        }
    }
}

Однако это не дает мне желаемого результата, Есть ли что-то, чего мне не хватает

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...