Android谷歌地图获得mutilple位置之间的最短路径

时间:2015-09-03 11:25:24

标签: android

我想找到用户当前位置的最短位置。 我使用distanceTo()和distanceBetween(),但它不起作用

我的Android应用程序的过程是在变量中自动初始化地点的位置,我想将它与多个位置进行比较,找到最短的位置并打印位置。

任何人都可以帮我解决我的问题吗?提前谢谢

1 个答案:

答案 0 :(得分:1)

试试这个,

public class Nav extends Fragment {

GoogleMap map;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Commons.applyFont(getActivity(), getView().findViewById(R.id.frame),
            "RobotoSlab-Light");
    map = ((SupportMapFragment) this.getChildFragmentManager()
            .findFragmentById(R.id.map)).getMap();
    map.setMyLocationEnabled(true);
    LatLng latLng = new LatLng(nav.sAddLat, nav.sAddLong);
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15.0f));
    map.addMarker(new MarkerOptions().position(new LatLng(nav.sAddLat,
            nav.sAddLong)));
    map.getUiSettings().setCompassEnabled(true);
    map.getUiSettings().setZoomControlsEnabled(true);
    CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(latLng).tilt(60).zoom(15.0f).bearing(300).build();
    map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    LatLng origin = new LatLng(nav.sAddLat, nav.sAddLong);
    LatLng dest = new LatLng(nav.dAddLat, nav.dAddLong);
    String url = getDirectionsUrl(origin, dest);
    DownloadTask downloadTask = new DownloadTask();
    downloadTask.execute(url);
}

private String getDirectionsUrl(LatLng origin, LatLng dest) {
    String str_origin = "origin=" + origin.latitude + ","
            + origin.longitude;
    String str_dest = "destination=" + dest.latitude + "," + dest.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;
    return url;
}

@SuppressLint("LongLogTag")
private String downloadUrl(String strUrl) throws IOException {
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(strUrl);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();
        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();
        br.close();
    } catch (Exception e) {
        Log.d("Exception while downloading url", e.toString());
    } finally {
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}

private class DownloadTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... url) {
        String data = "";
        try {
            data = downloadUrl(url[0]);
        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        return data;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        ParserTask parserTask = new ParserTask();
        parserTask.execute(result);
    }
}

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]);
            DirectionsJsonParser parser = new DirectionsJsonParser();
            routes = parser.parse(jObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return routes;
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        ArrayList<LatLng> points = null;
        PolylineOptions lineOptions = null;
        Log.e("results", result + "");
        if (result.size() < 1) {
            Toast.makeText(getActivity(), "No Points", 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);
            Log.e("points", path + "");
            for (int j = 0; j < path.size(); j++) {
                HashMap<String, String> point = path.get(j);
                if (j == 0) {
                    tvDistance.setText("Distance : "
                            + point.get("distance"));
                } else if (j == 1) {
                    tvTime.setText("Duration : " + point.get("duration"));
                } else if (j > 1) {
                    double lat = Double.parseDouble(point.get("lat"));
                    double lng = Double.parseDouble(point.get("lng"));
                    LatLng position = new LatLng(lat, lng);
                    points.add(position);
                }
            }
            lineOptions.addAll(points);
            lineOptions.width(2);
            lineOptions.color(Color.RED);
        }
        map.addPolyline(lineOptions);
    }
}

}