在反向地理编码点和当前位置之间画一条线

时间:2019-02-28 09:20:42

标签: android google-maps

我正在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();
        }
    }
}

但是它没有给我想要的输出,是否缺少我

0 个答案:

没有答案