Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 获得一条包含多个点的路线_Java_Android_Google Maps - Fatal编程技术网

Java 获得一条包含多个点的路线

Java 获得一条包含多个点的路线,java,android,google-maps,Java,Android,Google Maps,我有以下几点: list.add(new LatLng(51.410831451416016,16.195022583007812)); list.add(new LatLng(51.40906524658203,16.19700813293457)); list.add(new LatLng(51.406280517578125,16.200498580932617)); list.add(new LatLng(51.40361022949219,16.20193862915039)); li

我有以下几点:

list.add(new LatLng(51.410831451416016,16.195022583007812));
list.add(new LatLng(51.40906524658203,16.19700813293457));
list.add(new LatLng(51.406280517578125,16.200498580932617));
list.add(new LatLng(51.40361022949219,16.20193862915039));
list.add(new LatLng(51.400203704833984,16.20381736755371));
list.add(new LatLng(51.400081634521484,16.213804244995117));
list.add(new LatLng(51.40199661254883,16.216102600097656));
list.add(new LatLng(51.40852355957031,16.219417572021484));
list.add(new LatLng(51.43153762817383,16.23755645751953));
list.add(new LatLng(51.447242736816406,16.245569229125977));
list.add(new LatLng(51.45175552368164,16.234098434448242));
list.add(new LatLng(51.45286178588867,16.24496841430664));
list.add(new LatLng(51.46625900268555,16.2692928314209));
list.add(new LatLng(51.47911071777344,16.266849517822266));
list.add(new LatLng(51.50560760498047,16.268840789794922));
list.add(new LatLng(51.510677337646484,16.259723663330078));
list.add(new LatLng(51.510677337646484,16.259723663330078));
list.add(new LatLng(51.50559997558594,16.2688045501709));
list.add(new LatLng(51.476688385009766,16.267772674560547));
list.add(new LatLng(51.46686935424805,16.270612716674805));
list.add(new LatLng(51.451759338378906,16.234111785888672));
list.add(new LatLng(51.45033264160156,16.244768142700195));
list.add(new LatLng(51.44853591918945,16.24496841430664));
list.add(new LatLng(51.43154525756836,16.237483978271484));
list.add(new LatLng(51.40877151489258,16.21938133239746));
我想知道路线,把它画在地图上

我提出了一种生成两个点的方法

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 points = null;
            PolylineOptions lineOptions = null;
            MarkerOptions markerOptions = new MarkerOptions();

            for (int i = 0; i < result.size(); i++) {
                points = new ArrayList();
                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);

                    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(12);
                lineOptions.color(Color.RED);
                lineOptions.geodesic(true);

            }

            mMap.addPolyline(lineOptions);
        }
    }

    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";

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


        return url;
    }


    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", e.toString());
        } finally {
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }
私有类下载任务扩展了异步任务{
@凌驾
受保护的字符串doInBackground(字符串…url){
字符串数据=”;
试一试{
数据=下载url(url[0]);
}捕获(例外e){
Log.d(“后台任务”,例如toString());
}
返回数据;
}
@凌驾
受保护的void onPostExecute(字符串结果){
super.onPostExecute(结果);
ParserTask ParserTask=新的ParserTask();
执行(结果);
}
}
私有类ParserTask扩展了AsyncTask{
@凌驾
受保护列表doInBackground(字符串…jsonData){
JSONObject jObject;
列表路由=空;
试一试{
jObject=新的JSONObject(jsonData[0]);
DirectionsJSONParser=新的DirectionsJSONParser();
routes=parser.parse(jObject);
}捕获(例外e){
e、 printStackTrace();
}
返回路线;
}
@凌驾
受保护的void onPostExecute(列表结果){
ArrayList points=null;
PolylineOptions lineOptions=null;
MarkerOptions MarkerOptions=新MarkerOptions();
对于(int i=0;i

有时我有300个点,下载点1到2的路线,然后再下载点2到3的路线,等等。这样做更好吗?我所做的持续时间很长,我有很多信息

您正在寻找的是航路点。请参见“可选参数”部分

指定要沿路线包含的中间位置数组 起点和终点之间的路线,如通过或 中途停留地点。航路点通过引导路线改变路线 指定的位置

我建议您建立一条从第一个点到最后一个点的路线,中间点作为航路点传递

包含纬度/经度航路点的URL示例:

https://maps.googleapis.com/maps/api/directions/json?
origin=sydney,au&destination=perth,au
&waypoints=via:-37.81223%2C144.96254%7Cvia:-34.92788%2C138.60008
&key=YOUR_API_KEY

您要查找的是航路点。请参见“可选参数”部分

指定要沿路线包含的中间位置数组 起点和终点之间的路线,如通过或 中途停留地点。航路点通过引导路线改变路线 指定的位置

我建议您建立一条从第一个点到最后一个点的路线,中间点作为航路点传递

包含纬度/经度航路点的URL示例:

https://maps.googleapis.com/maps/api/directions/json?
origin=sydney,au&destination=perth,au
&waypoints=via:-37.81223%2C144.96254%7Cvia:-34.92788%2C138.60008
&key=YOUR_API_KEY

您可以使用此代码从您的航路点获取路线,我已在指南代码中对其进行了注释

public class DirectionFinder {

    // this is directio api URL
        private static final String DIRECTION_URL_API = "https://maps.googleapis.com/maps/api/directions/json?";
        // your api key
        private static final String GOOGLE_API_KEY = "YOUR_API_KEY";

        // your origin point latlong
        LatLng originlatlong;

        // your destinatio point latlong
        LatLng destinationlatlong;

        // your array list of waypoints
        ArrayList<LatLng> waypoints;


        // adding way points to arraylist
        void addwaypoints(){

            waypoints = new ArrayList<>()
            waypoints.add(new LatLng(51.410831451416016,16.195022583007812));
            waypoints.add(new LatLng(51.40906524658203,16.19700813293457));
            waypoints.add(new LatLng(51.406280517578125,16.200498580932617));
            waypoints.add(new LatLng(51.40361022949219,16.20193862915039));
            waypoints.add(new LatLng(51.400203704833984,16.20381736755371));
            waypoints.add(new LatLng(51.400081634521484,16.213804244995117));
            waypoints.add(new LatLng(51.40199661254883,16.216102600097656));
            waypoints.add(new LatLng(51.40852355957031,16.219417572021484));
            waypoints.add(new LatLng(51.43153762817383,16.23755645751953));
            waypoints.add(new LatLng(51.447242736816406,16.245569229125977));
            waypoints.add(new LatLng(51.45175552368164,16.234098434448242));
            waypoints.add(new LatLng(51.45286178588867,16.24496841430664));
            waypoints.add(new LatLng(51.46625900268555,16.2692928314209));
            waypoints.add(new LatLng(51.47911071777344,16.266849517822266));
            waypoints.add(new LatLng(51.50560760498047,16.268840789794922));
            waypoints.add(new LatLng(51.510677337646484,16.259723663330078));
            waypoints.add(new LatLng(51.510677337646484,16.259723663330078));
            waypoints.add(new LatLng(51.50559997558594,16.2688045501709));
            waypoints.add(new LatLng(51.476688385009766,16.267772674560547));
            waypoints.add(new LatLng(51.46686935424805,16.270612716674805));
            waypoints.add(new LatLng(51.451759338378906,16.234111785888672));
            waypoints.add(new LatLng(51.45033264160156,16.244768142700195));
            waypoints.add(new LatLng(51.44853591918945,16.24496841430664));
            waypoints.add(new LatLng(51.43154525756836,16.237483978271484));
            waypoints.add(new LatLng(51.40877151489258,16.21938133239746));

        }



        // your async task execute
    //new DirectionFinder().execute(); like this
        public void execute() throws UnsupportedEncodingException {

            new DownloadRawData().execute(createUrlwaypoints());
        }

        // url create with waypoints
        private String createUrlwaypoints() throws UnsupportedEncodingException {

            String wayPointss = "";
            for (int i = 0;i<waypoints.size();i++){

                if (i==(waypoints.size()-1)){
                    wayPointss += ""+waypoints.get(i).latitude+","+waypoints.get(i).longitude+"";
                }else {
                    wayPointss += "" + waypoints.get(i).latitude + "," + waypoints.get(i).longitude + "|";
                }
            }

            return DIRECTION_URL_API + "origin=" + originlatlong.latitude+","+originlatlong.longitude + "&destination=" + destinationlatlong.latitude+","+destinationlatlong.longitude + "&waypoints=optimize:true|"+wayPointss+"|&key=" + GOOGLE_API_KEY;
        }

        // async task to download routes
        private class DownloadRawData extends AsyncTask<String, Void, String> {

            @Override
            protected String doInBackground(String... params) {
                String link = params[0];
                try {
                    URL url = new URL(link);
                    InputStream is = url.openConnection().getInputStream();
                    StringBuffer buffer = new StringBuffer();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));

                    String line;
                    while ((line = reader.readLine()) != null) {
                        buffer.append(line + "\n");
                    }

                    return buffer.toString();

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String res) {
                try {
                    parseJSon(res);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        private void parseJSon(String data) throws JSONException {
            if (data == null)
                return;


            // here Route is my getter setter model class that have some parametes like distance,duration,etc..
            List<Route> routes = new ArrayList<Route>();
            JSONObject jsonData = new JSONObject(data);
            JSONArray jsonRoutes = jsonData.getJSONArray("routes");
            for (int i = 0; i < jsonRoutes.length(); i++) {
                JSONObject jsonRoute = jsonRoutes.getJSONObject(i);
                Route route = new Route();

                JSONObject overview_polylineJson = jsonRoute.getJSONObject("overview_polyline");
                JSONArray jsonLegs = jsonRoute.getJSONArray("legs");
                JSONObject jsonLeg = jsonLegs.getJSONObject(0);
                JSONObject jsonDistance = jsonLeg.getJSONObject("distance");
                JSONObject jsonDuration = jsonLeg.getJSONObject("duration");
                JSONObject jsonEndLocation = jsonLeg.getJSONObject("end_location");
                JSONObject jsonStartLocation = jsonLeg.getJSONObject("start_location");
                JSONArray jsonArray = jsonRoute.getJSONArray("waypoint_order");

                route.distance = new Distance(jsonDistance.getString("text"), jsonDistance.getInt("value"));
                route.duration = new Duration(jsonDuration.getString("text"), jsonDuration.getInt("value"));
                route.endAddress = jsonLeg.getString("end_address");
                route.startAddress = jsonLeg.getString("start_address");
                route.startLocation = new LatLng(jsonStartLocation.getDouble("lat"), jsonStartLocation.getDouble("lng"));
                route.endLocation = new LatLng(jsonEndLocation.getDouble("lat"), jsonEndLocation.getDouble("lng"));
                route.points = decodePolyLine(overview_polylineJson.getString("points"));
                int[] indexes = new int[jsonArray.length()];

                for (int index = 0;index<jsonArray.length();index++){
                    indexes[index] = (int) jsonArray.get(index);
                }

                route.indexes = indexes;
                routes.add(route);
            }

            // read all data and you can here put code to plot route on map
            drawOnMap(routes);
        }

        private List<LatLng> decodePolyLine(final String poly) {
            int len = poly.length();
            int index = 0;
            List<LatLng> decoded = new ArrayList<LatLng>();
            int lat = 0;
            int lng = 0;

            while (index < len) {
                int b;
                int shift = 0;
                int result = 0;
                do {
                    b = poly.charAt(index++) - 63;
                    result |= (b & 0x1f) << shift;
                    shift += 5;
                } while (b >= 0x20);
                int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
                lat += dlat;

                shift = 0;
                result = 0;
                do {
                    b = poly.charAt(index++) - 63;
                    result |= (b & 0x1f) << shift;
                    shift += 5;
                } while (b >= 0x20);
                int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
                lng += dlng;

                decoded.add(new LatLng(
                        lat / 100000d, lng / 100000d
                ));
            }

            return decoded;
        }

        void drawOnMap(ArrayList<Route> routes){

            polyLinePaths = new ArrayList<>();
            originMarkers = new ArrayList<>();
            destinationMarker = new ArrayList<>();

            for (Route route : routes) {

                mMap.addMarker(new MarkerOptions()
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.startflags))
                        .title(route.startAddress)
                        .position(originPoints));

                mMap.addMarker(new MarkerOptions()
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.endflags))
                        .title(route.endAddress)
                        .position(destinationPoints));

                PolylineOptions polylineOptions = new PolylineOptions()
                        .geodesic(true)
                        .color(getResources().getColor(R.color.colorPrimary))
                        .width(5);

                if (wayPoints!=null){
                    for (int i = 0;i<wayPoints.size();i++){
                        mMap.addMarker(new MarkerOptions()
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.busstopp))
                                .title(wayPoints.get(i).getStopName())
                                .position(wayPoints.get(i).getLatLng()));
                    }
                }

                for (int i = 0; i < route.points.size(); i++) {
                    polylineOptions.add(route.points.get(i));

                }
                polyLinePaths.add(mMap.addPolyline(polylineOptions));
        }

    }
public类DirectionFinder{
//这是directio api URL
私有静态最终字符串方向\u URL\u API=”https://maps.googleapis.com/maps/api/directions/json?";
//您的api密钥
私有静态最终字符串GOOGLE\u API\u KEY=“YOUR\u API\u KEY”;
//你的起点太长了
LatLng originlatlong;
//你的目的地拉特朗
LatLng Destination Atlong;
//您的航路点数组列表
ArrayList航路点;
//向arraylist添加路径点
void addwaypoints(){
航路点=新阵列列表()
添加(新LatLng(51.410831451416016,16.195022583007812));
航路点。添加(n)