【问题标题】:Displaying multiple routes using Directions API in Android在 Android 中使用 Directions API 显示多条路线
【发布时间】:2013-10-17 21:47:12
【问题描述】:

我正在使用此类在地图上显示路线。问题是它只显示一条路线。我想要做的是在地图上显示多条备用路线。即使服务器响应有多个路由,它也只解析第一个路由并显示它。我应该做些什么改变来显示谷歌服务器返回的所有路由。这是我的课程。

public class GMapV2Direction {
    public final static String MODE_DRIVING = "driving";
    public final static String MODE = "walking";
    public final static String MODE_WALKING = "walking";

    public GMapV2Direction() { }

    public Document getDocument(LatLng start, LatLng end, String mode) {
        String url = "http://maps.googleapis.com/maps/api/directions/xml?" 
                + "origin=" + start.latitude + "," + start.longitude  
                + "&destination=" + end.latitude + "," + end.longitude 
                + "&sensor=false&units=metric&mode="+MODE+"alternatives=true";

        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse response = httpClient.execute(httpPost, localContext);
            InputStream in = response.getEntity().getContent();
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(in);
            return doc;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getDurationText (Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        Node node1 = nl1.item(0);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
        Log.i("DurationText", node2.getTextContent());
        return node2.getTextContent();
    }

    public int getDurationValue (Document doc) {

        NodeList nl1 = doc.getElementsByTagName("duration");
        Node node1 = nl1.item(0);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));
        Log.i("DurationValue", node2.getTextContent());
        return Integer.parseInt(node2.getTextContent());

    }

    public String getDistanceText (Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        Node node1 = nl1.item(0);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
        Log.i("DistanceText", node2.getTextContent());
        return node2.getTextContent();
    }

    public int getDistanceValue (Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        Node node1 = nl1.item(0);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));
        Log.i("DistanceValue", node2.getTextContent());
        return Integer.parseInt(node2.getTextContent());
    }

    public String getStartAddress (Document doc) {
        NodeList nl1 = doc.getElementsByTagName("start_address");
        Node node1 = nl1.item(0);
        Log.i("StartAddress", node1.getTextContent());
        return node1.getTextContent();
    }

    public String getEndAddress (Document doc) {
        NodeList nl1 = doc.getElementsByTagName("end_address");
        Node node1 = nl1.item(0);
        Log.i("EndAddress", node1.getTextContent());
        return node1.getTextContent();
    }

    public String getCopyRights (Document doc) {
        NodeList nl1 = doc.getElementsByTagName("copyrights");
        Node node1 = nl1.item(0);
        Log.i("CopyRights", node1.getTextContent());
        return node1.getTextContent();
    }

    public ArrayList<LatLng> getDirection (Document doc) {
        NodeList nl1, nl2, nl3;
        ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
        nl1 = doc.getElementsByTagName("step");
        if (nl1.getLength() > 0) {
            for (int i = 0; i < nl1.getLength(); i++) {
                Node node1 = nl1.item(i);
                nl2 = node1.getChildNodes();

                Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
                nl3 = locationNode.getChildNodes();
                Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
                double lat = Double.parseDouble(latNode.getTextContent());
                Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                double lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));

                locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "points"));
                ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
                for(int j = 0 ; j < arr.size() ; j++) {
                    listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude));
                }

                locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "lat"));
                lat = Double.parseDouble(latNode.getTextContent());
                lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));
            }
        }

        return listGeopoints;
    }

    private int getNodeIndex(NodeList nl, String nodename) {
        for(int i = 0 ; i < nl.getLength() ; i++) {
            if(nl.item(i).getNodeName().equals(nodename))
                return i;
        }
        return -1;
    }

    private ArrayList<LatLng> decodePoly(String encoded) {
        ArrayList<LatLng> poly = new ArrayList<LatLng>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;
        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.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 = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng position = new LatLng((double) lat / 1E5, (double) lng / 1E5);
            poly.add(position);
        }
        return poly;
    }
}

【问题讨论】:

    标签: android google-maps google-maps-android-api-2 directions


    【解决方案1】:

    我认为您不必获取 Google Server 的响应并在 Document 中对其进行解析,否则您可以从 InputStream 进行转换> 到 String 使用:

    private String convertStreamToString(final InputStream input) throws Exception {
        try {
            final BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            final StringBuffer sBuf = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sBuf.append(line);
            }
            return sBuf.toString();
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                input.close();
            } catch (Exception e) {
                throw e;
            }
        }
    

    那么您必须将响应解析为 JSONObject

    JSONObject jSONObject = new JSONObject(string);
    

    然后你会得到名为 routes

    JSONArray
    JSONArray routeJSONArray = jSONObject.getJSONArray("routes");
    

    现在您可以通过从 JSONArray 获取其索引来开始从每个路由中获取数据。

    我已经编写了一段 sn-p 代码作为路由的模型

    Route.java

    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.List;
    
    import android.content.Context;
    
    import com.google.android.gms.maps.model.Polyline;
    
    public class Route implements Serializable {
    
        private static final long serialVersionUID = 1L;
        private Bound bounds;
        private String copyrights;
        private List<Leg> legs;
        private Polyline overviewPolyLine;
        private String summary;
    
        public Route(Context context) {
            legs = new ArrayList<Leg>();
        }
    
        public Bound getBounds() {
            return bounds;
        }
    
        public void setBounds(Bound bounds) {
            this.bounds = bounds;
        }
    
        public String getCopyrights() {
            return copyrights;
        }
    
        public void setCopyrights(String copyrights) {
            this.copyrights = copyrights;
        }
    
        public List<Leg> getLegs() {
            return legs;
        }
    
        public void setLegs(List<Leg> legs) {
            this.legs = legs;
        }
    
        public void addLeg(Leg leg) {
            this.legs.add(leg);
        }
    
        public Polyline getOverviewPolyLine() {
            return overviewPolyLine;
        }
    
        public void setOverviewPolyLine(Polyline overviewPolyLine) {
            this.overviewPolyLine = overviewPolyLine;
        }
    
        public String getSummary() {
            return summary;
        }
    
        public void setSummary(String summary) {
            this.summary = summary;
        }
    
        public static long getSerialversionuid() {
            return serialVersionUID;
        }
    
    }
    

    Bound.java

    import com.google.android.gms.maps.model.LatLng;
    
    public class Bound {
        private LatLng northEast;
        private LatLng southWest;
        public LatLng getNorthEast() {
            return northEast;
        }
        public void setNorthEast(LatLng northEast) {
            this.northEast = northEast;
        }
        public LatLng getSouthWest() {
            return southWest;
        }
        public void setSouthWest(LatLng southWest) {
            this.southWest = southWest;
        }
    }
    

    Leg.java

    import java.util.ArrayList;
    import java.util.List;
    
    import com.google.android.gms.maps.model.LatLng;
    
    public class Leg {
        private Distance distance;
        private Duration duration;
        private String endAddress;
        private LatLng endLocation;
        private String startAddress;
        private LatLng startLocation;
        private List<Step> steps;
    
        public Leg() {
            steps = new ArrayList<Step>();
        }
    
        public Distance getDistance() {
            return distance;
        }
    
        public void setDistance(Distance distance) {
            this.distance = distance;
        }
    
        public Duration getDuration() {
            return duration;
        }
    
        public void setDuration(Duration duration) {
            this.duration = duration;
        }
    
        public String getEndAddress() {
            return endAddress;
        }
    
        public void setEndAddress(String endAddress) {
            this.endAddress = endAddress;
        }
    
        public LatLng getEndLocation() {
            return endLocation;
        }
    
        public void setEndLocation(LatLng endLocation) {
            this.endLocation = endLocation;
        }
    
        public String getStartAddress() {
            return startAddress;
        }
    
        public void setStartAddress(String startAddress) {
            this.startAddress = startAddress;
        }
    
        public LatLng getStartLocation() {
            return startLocation;
        }
    
        public void setStartLocation(LatLng startLocation) {
            this.startLocation = startLocation;
        }
    
        public List<Step> getSteps() {
            return steps;
        }
    
        public void setSteps(List<Step> steps) {
            this.steps = steps;
        }
    
        public void addStep(Step step) {
            this.steps.add(step);
        }
    
    }
    

    Distance.java

    public class Distance {
        private String text;
        private long value;
    
        public Distance(String text, long value) {
            this.text = text;
            this.value = value;
        }
    
        public String getText() {
            return text;
        }
    
        public void setText(String text) {
            this.text = text;
        }
    
        public long getValue() {
            return value;
        }
    
        public void setValue(long value) {
            this.value = value;
        }
    
    }
    

    Duration.java

    public class Duration {
        public Duration(String text, long value) {
            this.text = text;
            this.value = value;
        }
    
        private String text;
        private long value;
    
        public String getText() {
            return text;
        }
    
        public void setText(String text) {
            this.text = text;
        }
    
        public long getValue() {
            return value;
        }
    
        public void setValue(long value) {
            this.value = value;
        }
    
    }
    

    Step.java

    import java.util.List;
    
    import android.annotation.SuppressLint;
    import android.content.Context;
    import android.graphics.drawable.Drawable;
    
    import com.google.android.gms.maps.model.LatLng;
    import com.nweave.etaxi.driver.R;
    
    public class Step {
        private Distance distance;
        private Duration duration;
        private LatLng endLocation;
        private LatLng startLocation;
        private String htmlInstructions;
        private String travelMode;
        private List<LatLng> points;
    
        public List<LatLng> getPoints() {
            return points;
        }
    
        public void setPoints(List<LatLng> points) {
            this.points = points;
        }
    
        public Distance getDistance() {
            return distance;
        }
    
        public void setDistance(Distance distance) {
            this.distance = distance;
        }
    
        public Duration getDuration() {
            return duration;
        }
    
        public void setDuration(Duration duration) {
            this.duration = duration;
        }
    
        public LatLng getEndLocation() {
            return endLocation;
        }
    
        public void setEndLocation(LatLng endLocation) {
            this.endLocation = endLocation;
        }
    
        public LatLng getStartLocation() {
            return startLocation;
        }
    
        public void setStartLocation(LatLng startLocation) {
            this.startLocation = startLocation;
        }
    
        public String getHtmlInstructions() {
            return htmlInstructions;
        }
    
        public void setHtmlInstructions(String htmlInstructions) {
            this.htmlInstructions = htmlInstructions;
        }
    
        public String getTravelMode() {
            return travelMode;
        }
    
        public void setTravelMode(String travelMode) {
            this.travelMode = travelMode;
        }
    }
    

    解析函数将是

    public List<Route> parse(String routesJSONString) throws Exception {
        try {
            List<Route> routeList = new ArrayList<Route>();
            final JSONObject jSONObject = new JSONObject(routesJSONString);
            JSONArray routeJSONArray = jSONObject.getJSONArray(ROUTES);
            Route route;
            JSONObject routesJSONObject;
            for (int m = 0; m < routeJSONArray.length(); m++) {
                route = new Route(context);
                routesJSONObject = routeJSONArray.getJSONObject(m);
                JSONArray legsJSONArray;
                route.setSummary(routesJSONObject.getString(SUMMARY));
                legsJSONArray = routesJSONObject.getJSONArray(LEGS);
                JSONObject legJSONObject;
                Leg leg;
                JSONArray stepsJSONArray;
                for (int b = 0; b < legsJSONArray.length(); b++) {
                    leg = new Leg();
                    legJSONObject = legsJSONArray.getJSONObject(b);
                    leg.setDistance(new Distance(legJSONObject.optJSONObject(DISTANCE).optString(TEXT), legJSONObject.optJSONObject(DISTANCE).optLong(VALUE)));
                    leg.setDuration(new Duration(legJSONObject.optJSONObject(DURATION).optString(TEXT), legJSONObject.optJSONObject(DURATION).optLong(VALUE)));
                    stepsJSONArray = legJSONObject.getJSONArray(STEPS);
                    JSONObject stepJSONObject, stepDurationJSONObject, legPolyLineJSONObject, stepStartLocationJSONObject, stepEndLocationJSONObject;
                    Step step;
                    String encodedString;
                    LatLng stepStartLocationLatLng, stepEndLocationLatLng;
                    for (int i = 0; i < stepsJSONArray.length(); i++) {
                        stepJSONObject = stepsJSONArray.getJSONObject(i);
                        step = new Step();
                        JSONObject stepDistanceJSONObject = stepJSONObject.getJSONObject(DISTANCE);
                        step.setDistance(new Distance(stepDistanceJSONObject.getString(TEXT), stepDistanceJSONObject.getLong(VALUE)));
                        stepDurationJSONObject = stepJSONObject.getJSONObject(DURATION);
                        step.setDuration(new Duration(stepDurationJSONObject.getString(TEXT), stepDurationJSONObject.getLong(VALUE)));
                        stepEndLocationJSONObject = stepJSONObject.getJSONObject(END_LOCATION);
                        stepEndLocationLatLng = new LatLng(stepEndLocationJSONObject.getDouble(LATITUDE), stepEndLocationJSONObject.getDouble(LONGITUDE));
                        step.setEndLocation(stepEndLocationLatLng);
                        step.setHtmlInstructions(stepJSONObject.getString(HTML_INSTRUCTION));
                        legPolyLineJSONObject = stepJSONObject.getJSONObject(POLYLINE);
                        encodedString = legPolyLineJSONObject.getString(POINTS);
                        step.setPoints(decodePolyLines(encodedString));
                        stepStartLocationJSONObject = stepJSONObject.getJSONObject(START_LOCATION);
                        stepStartLocationLatLng = new LatLng(stepStartLocationJSONObject.getDouble(LATITUDE), stepStartLocationJSONObject.getDouble(LONGITUDE));
                        step.setStartLocation(stepStartLocationLatLng);
                        leg.addStep(step);
                    }
                    route.addLeg(leg);
                }
                routeList.add(route);
            }
            return routeList;
        } catch (Exception e) {
            throw e;
        }
    

    关于 Step Image 有一个 HTML 指令和另一个名为 ma​​neuver 的字段,您将根据该字段选择您的图像

    我希望这会有所帮助;)

    【讨论】:

    • 您节省了我的时间 :) 我实际上打算编写所有这些模型并逐步解析 JSON,谢谢 :)
    • @Ajji 这是我的荣幸
    • @3amoura:我有一个困惑......你为什么在 Route.java 中使用 Serializable ??
    • @R.K,不需要使其可序列化,我只是忘了删除它,我想通过 Intent Extras 将 Route 从一个 Activity 传递到另一个 Activity。但是这里的 Serializable 不是强制性的。很抱歉造成这种混乱。
    • 好的...谢谢..您的回答...效果很好@3amoura
    【解决方案2】:

    我认为你可以这样做

    LatLng origin = sourcePosition;
         LatLng dest = destPosition;
    
      DownloadTask1 downloadTask = new DownloadTask1();
      String url = downloadTask.getDirectionsUrl1(origin, dest);                   
      downloadTask.execute(url);
    

    DownloadTask1 类

     private class DownloadTask1 extends AsyncTask<String, Void, String> {
    
            // Downloading data in non-ui thread
            @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) {
                    Log.d("Background Task", e.toString());
                }
                return data;
            }
    
            // Executes in UI thread, after the execution of
            // doInBackground()
            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
    
                ParserTask1 parserTask = new ParserTask1();
    
                // Invokes the thread for parsing the JSON data
                parserTask.execute(result);
            }
    
    
            private String getDirectionsUrl1(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&alternatives=true&units=metric&mode=driving";
                //&alternatives=true&units=metric&mode=driving
                // Building the parameters to the web service
                String parameters = str_origin + "&" + str_dest + "&" + sensor;
    
                // 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;
            }
        }
    

    downloadUrl() 方法

    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();
    
                br.close();
    
            }catch(Exception e){
                e.printStackTrace();
                //Log.d("Exception while downloading url", e.toString());
            }finally{
                iStream.close();
                urlConnection.disconnect();
            }
            return data;
        } 
    

    ParserTask1 类

    private class ParserTask1 extends AsyncTask<String, Integer, List<List<List<HashMap<String, String>>>>> {
    
            // Parsing the data in non-ui thread
            @Override
            protected List<List<List<HashMap<String, String>>>> doInBackground(String... jsonData) {
    
                JSONObject jObject;
                List<List<List<HashMap<String, String>>>> routes = null;
    
                try {
                    jObject = new JSONObject(jsonData[0]);
                    DirectionsJSONParser parser = new DirectionsJSONParser();
    
                    // Starts parsing data
                    routes = parser.parse(jObject);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return routes;
            }
    
            // Executes in UI thread, after the parsing process
            @Override
            protected void onPostExecute(List<List<List<HashMap<String, String>>>> result) {
                ArrayList<LatLng> points = null;
                PolylineOptions lineOptions = new PolylineOptions();
    
                PolylineOptions lineOptions1 = null;
                MarkerOptions markerOptions = new MarkerOptions();
                String distance = "";
                String duration = "";
    
                Integer size1 = 0;
                Integer size2 = 0;
                Integer size3 = 0;
    //            Log.d(SHETTY, "onPostExecute: result set "+result.size());
    
    
                List<LatLng> aline1 = new ArrayList<LatLng>();
                List<LatLng> aline2 = new ArrayList<LatLng>();
                List<LatLng> aline3 = new ArrayList<LatLng>();
    
    
                if (result != null) {
                    int i = 0;
                    Log.d(SHETTY, "onPostExecute: result size " + result.size());
    
                    while (i < result.size()) {
    
                        //  for(int i=0;i<result.size();i++){
                        //result.size()
                        //int g= i-1;
                        points = new ArrayList<LatLng>();
                        // lineOptions = new PolylineOptions();
                        // if(i==1){
    
                        // }else{
                        List<List<HashMap<String, String>>> path1 = result.get(i);
    
                        for (int s = 0; s < path1.size(); s++) {
                            Log.d("pathsize1", path1.size() + "");
    
                            // Fetching i-th route
                            List<HashMap<String, String>> path = path1.get(s);
                            Log.d("pathsize", path.size() + "");
                            // Fetching all the points in i-th route
    
                            for (int j = 0; j < path.size(); j++) {
                                lineOptions1 = new PolylineOptions();
                                HashMap<String, String> point = path.get(j);
                                //  points = new ArrayList<LatLng>();
                                //                    if(j==0){    // Get distance from the list
                                //                        distance = (String)point.get("distance");
                                //                        continue;
                                //                    }else if(j==1){ // Get duration from the list
                                //                        duration = (String)point.get("duration");
                                //                        continue;
                                //                    }
                                double lat = Double.parseDouble(point.get("lat"));
                                double lng = Double.parseDouble(point.get("lng"));
                                LatLng position = new LatLng(lat, lng);
                                // Log.d("latlng", position.toString());
                                points.add(position);
    
    
                            }
                            //                lineOptions.addAll(points);
                            //                lineOptions.width(5);
                            //                lineOptions.color(Color.BLUE);
                            //                map.addPolyline(lineOptions);
    
                        }
                        // }
                        if (i == 0) {
    
    
    //                        line1.addAll(points);
    //                        mMap.addPolyline(line1);
    
                            size1 = points.size();
    
                            aline1.addAll(points);
                        } else if (i == 1) {
    
    
    //                        line2.addAll(points);
    //                        mMap.addPolyline(line2);
    
                            aline2.addAll(points);
                            size2 = points.size();
                        } else if (i == 2) {
    
    
    //                        line3.addAll(points);
    //                        mMap.addPolyline(line3);
    
                            aline3.addAll(points);
                            size3 = points.size();
                        }
                        // Adding all the points in the route to LineOptions
                        i++;
    
    
                    }
                    // Drawing polyline in the Google Map for the i-th route
                    // map.addPolyline(lineOptions);
                }
    
                if (size3 != 0)
                {
    
                    if ((size1 > size2 && size1 > size3)) {
                        if (size2 > size3) {
                            PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
                            PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
                            PolylineOptions line3 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue));
    
                            line1.addAll(aline1);
                            line2.addAll(aline2);
                            line3.addAll(aline3);
    
                            mMap.addPolyline(line1);
                            mMap.addPolyline(line2);
                            mMap.addPolyline(line3);
    
    
                            Log.d(SHETTY, "onPostExecute: 3110 ");
                        } else {
    
                            PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
                            PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue));
                            PolylineOptions line3 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
    
                            line1.addAll(aline1);
                            line2.addAll(aline2);
                            line3.addAll(aline3);
    
                            mMap.addPolyline(line1);
                            mMap.addPolyline(line3);
    
                            mMap.addPolyline(line2);
    
    
                            Log.d(SHETTY, "onPostExecute: 3127 ");
                        }
                    } else if ((size2 > size1 && size2 > size3)) {
                        if (size1 > size3) {
                            PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
                            PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
                            PolylineOptions line3 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue));
    
                            line1.addAll(aline1);
                            line2.addAll(aline2);
                            line3.addAll(aline3);
    
                            mMap.addPolyline(line1);
                            mMap.addPolyline(line2);
    
                            mMap.addPolyline(line3);
    
    
                            Log.d(SHETTY, "onPostExecute: 3147 ");
                        } else {
    
                            PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue));
                            PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
                            PolylineOptions line3 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
    
                            line1.addAll(aline1);
                            line2.addAll(aline2);
                            line3.addAll(aline3);
    
    
                            mMap.addPolyline(line2);
                            mMap.addPolyline(line3);
    
                            mMap.addPolyline(line1);
    
                            Log.d(SHETTY, "onPostExecute: 3164 ");
                        }
                    } else if ((size3 > size1 && size3 > size2)) {
                        if (size1 > size2) {
                            PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
                            PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue));
                            PolylineOptions line3 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
    
                            line1.addAll(aline1);
                            line2.addAll(aline2);
                            line3.addAll(aline3);
    
    
                            mMap.addPolyline(line3);
                            mMap.addPolyline(line1);
                            mMap.addPolyline(line2);
    
                            Log.d(SHETTY, "onPostExecute: 3182 ");
                        } else {
                            PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue));
                            PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
                            PolylineOptions line3 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
    
                            line1.addAll(aline1);
                            line2.addAll(aline2);
                            line3.addAll(aline3);
    
                            mMap.addPolyline(line3);
                            mMap.addPolyline(line2);
    
                            mMap.addPolyline(line1);
    
                            Log.d(SHETTY, "onPostExecute: 3196 ");
                        }
                    } else {
                        System.out.println("ERROR!");
                    }
    
            }else if(size2!=0)
                {
                    if(size1>size2){
    
                        PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
                        PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue));
    
    
                        line1.addAll(aline1);
                        line2.addAll(aline2);
    
                        mMap.addPolyline(line1);
                        mMap.addPolyline(line2);
    
                    }else
                    {
                        PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue));
                        PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey));
    
                        line1.addAll(aline1);
                        line2.addAll(aline2);
    
                        mMap.addPolyline(line2);
                        mMap.addPolyline(line1);
                    }
    
    
    
                }
                else if(size1!=0){
                    PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue));
                    line1.addAll(aline1);
                    mMap.addPolyline(line1);
                }
    
            }
    
    
    
    
            }
    

    现在为解析 JObject 创建 DirectionsJSONParser 类

    public class DirectionsJSONParser {
    
        /**
         * Receives a JSONObject and returns a list of lists containing latitude and
         * longitude
         */
        public List<List<List<HashMap<String,String>>>> parse(JSONObject jObject){
    
            List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
            List<List<List<HashMap<String,String>>>> routes1 = new ArrayList<List<List<HashMap<String,String>>>>() ;
            JSONArray jRoutes = null;
            JSONArray jLegs = null;
            JSONArray jSteps = null;
    
            try {
    
                jRoutes = jObject.getJSONArray("routes");
    
                /** Traversing all routes */
                for(int i=0;i<jRoutes.length();i++){
                    jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
                    List path = new ArrayList<HashMap<String, String>>();
                    List path1 = new ArrayList<ArrayList<HashMap<String,String>>>();
    
                    // Log.d("legs",jLegs.toString());
                    /** Traversing all legs */
                    for(int j=0;j<jLegs.length();j++){
                        HashMap<String, String> hm1 = new HashMap<String, String>();
                        jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
                        // Log.d("steps",jSteps.toString());
                        /** Traversing all steps */
                        for(int k=0;k<jSteps.length();k++){
    
                            String polyline = "";
                            polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
                            List<LatLng> list = decodePoly(polyline);
                            //  Log.d("polyline",polyline.toString());
                            /** Traversing all points */
    
                            for(int l=0;l<list.size();l++){
                                HashMap<String, String>    hm = new HashMap<String, String>();
                                hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
                                hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
    
                                path.add(hm);
                                //  Log.d("lat", Double.toString(((LatLng)list.get(l)).latitude));
                                //  Log.d("lng", Double.toString(((LatLng)list.get(l)).longitude));
                            }
    
                        }
    
                        path1.add(path);
    
                    }
                    routes1.add(path1);
                }
    
            } catch (JSONException e) {
                e.printStackTrace();
            }catch (Exception e){
            }
    
            return routes1;
        }
        /**
         * Method to decode polyline points
         * Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
         * */
        private List<LatLng> decodePoly(String encoded) {
    
            List<LatLng> poly = new ArrayList<LatLng>();
            int index = 0, len = encoded.length();
            int lat = 0, lng = 0;
    
            while (index < len) {
                int b, shift = 0, result = 0;
                do {
                    b = encoded.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 = encoded.charAt(index++) - 63;
                    result |= (b & 0x1f) << shift;
                    shift += 5;
                } while (b >= 0x20);
                int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
                lng += dlng;
    
                LatLng p = new LatLng((((double) lat / 1E5)),
                        (((double) lng / 1E5)));
                poly.add(p);
            }
    
            return poly;
        }
    
    }
    

    最后,您将获得蓝色的主要路线和灰色的替代路线。希望对您有所帮助。

    【讨论】:

      【解决方案3】:

      这应该可行。在我的应用程序上测试。

      protected void onPostExecute(String s) {
          try {
              JSONObject jsonObject = new JSONObject(s);
              JSONArray jsonArrayRoute = jsonObject.getJSONArray("routes");
              JSONObject jsonObjectRoute;
              int route =  jsonArrayRoute.length();
                  for (int m = 0; m < route; m++) {
                      jsonObjectRoute = jsonArrayRoute.getJSONObject(m);
                      JSONArray jsonArrayLegs;
                      jsonArrayLegs = jsonObjectRoute.getJSONArray("legs");
                      JSONObject jsonObjectLegs;
                      JSONArray jsonArraySteps;
                      for (int b = 0; b < jsonArrayLegs.length(); b++) {
                          jsonObjectLegs = jsonArrayLegs.getJSONObject(b);
                          jsonArraySteps = jsonObjectLegs.getJSONArray("steps");
                          JSONObject jsonObjectSteps, jsonObjectLegPolyline;
                          String[] polylineArray = new String[jsonArraySteps.length()];
                          for (int i = 0; i < jsonArraySteps.length(); i++) {
                              jsonObjectSteps = jsonArraySteps.getJSONObject(i);
                              jsonObjectLegPolyline = jsonObjectSteps.getJSONObject("polyline");
                              String polygone = jsonObjectLegPolyline.getString("points");
                              polylineArray[i] = polygone;
                          }
                          int count2 = polylineArray.length;
                          for (int i = 0; i < count2; i++) {
                              mGoogleMap.addPolyline((new PolylineOptions())
                                      .color(Color.BLUE)
                                      .width(10)
                                      .clickable(true)
                                      .addAll(PolyUtil.decode(polylineArray[i])));
                          }
                      }
              } catch (JSONException e) {
              e.printStackTrace();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-13
        • 2015-10-07
        • 1970-01-01
        • 2020-07-22
        • 2023-02-12
        相关资源
        最近更新 更多