显示使用方向API在Android的多条路线 [英] Displaying multiple routes using Directions API in Android

查看:230
本文介绍了显示使用方向API在Android的多条路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这个类来显示在地图上的路线。的问题是,它仅显示一条路由。我想要做的就是在地图上显示多个备用路由。甚至认为服务器响应具有多条路线,它只是解析第一条路线并显示。我应该什么样的变化来显示所有的路线,谷歌服务器returns.Here是我的课。

 公共类GMapV2Direction {
    公共最后静态字符串MODE_DRIVING =驾驶;
    公共最后静态字符串MODE =行走;
    公共最后静态字符串MODE_WALKING =行走;

    公共GMapV2Direction(){}

    公开文件getDocument(经纬度开始,经纬度结束,字符串模式){
        字符串URL =htt​​p://maps.googleapis.com/maps/api/directions/xml?
                +原产地=+ start.latitude +,+ start.longitude
                +与&目的地=+ end.latitude +,+ end.longitude
                +&放大器,传感器=假放;单位=指标和放大器;模式=+ MODE +替代品=真;

        尝试 {
            HttpClient的HttpClient的=新DefaultHttpClient();
            HttpContext的localContext =新BasicHttpContext();
            HttpPost httpPost =新HttpPost(URL);
            HTT presponse响应= httpClient.execute(httpPost,localContext);
            。InputStream的时间= response.getEntity()的getContent();
            DocumentBuilder的建设者= DocumentBuilderFactory.newInstance()newDocumentBuilder()。
            文档DOC = builder.parse(中);
            返回文档;
        }赶上(例外五){
            e.printStackTrace();
        }
        返回null;
    }

    公共字符串getDurationText(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(期限);
        节点节点1 = nl1.item(0);
        节点列表NL2 = node1.getChildNodes();
        节点节点2 = nl2.item(getNodeIndex(NL2,文本));
        Log.i(DurationText,node2.getTextContent());
        返回node2.getTextContent();
    }

    公众诠释getDurationValue(DOC文件){

        节点列表NL1 = doc.getElementsByTagName(期限);
        节点节点1 = nl1.item(0);
        节点列表NL2 = node1.getChildNodes();
        节点节点2 = nl2.item(getNodeIndex(NL2,值));
        Log.i(DurationValue,node2.getTextContent());
        返回的Integer.parseInt(node2.getTextContent());

    }

    公共字符串getDistanceText(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(距离);
        节点节点1 = nl1.item(0);
        节点列表NL2 = node1.getChildNodes();
        节点节点2 = nl2.item(getNodeIndex(NL2,文本));
        Log.i(DistanceText,node2.getTextContent());
        返回node2.getTextContent();
    }

    公众诠释getDistanceValue(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(距离);
        节点节点1 = nl1.item(0);
        节点列表NL2 = node1.getChildNodes();
        节点节点2 = nl2.item(getNodeIndex(NL2,值));
        Log.i(DistanceValue,node2.getTextContent());
        返回的Integer.parseInt(node2.getTextContent());
    }

    公共字符串getStartAddress(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(START_ADDRESS);
        节点节点1 = nl1.item(0);
        Log.i(StartAddress开始,node1.getTextContent());
        返回node1.getTextContent();
    }

    公共字符串getEndAddress(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(end_address);
        节点节点1 = nl1.item(0);
        Log.i(EndAddress,node1.getTextContent());
        返回node1.getTextContent();
    }

    公共字符串getCop​​yRights(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(著作权);
        节点节点1 = nl1.item(0);
        Log.i(著作权,node1.getTextContent());
        返回node1.getTextContent();
    }

    公众的ArrayList<经纬度> getDirection(DOC文件){
        节点列表NL1,NL2,NL3;
        ArrayList的<经纬度> listGeopoints =新的ArrayList<经纬度>();
        NL1 = doc.getElementsByTagName(步);
        如果(nl1.getLength()大于0){
            的for(int i = 0; I< nl1.getLength();我++){
                节点节点1 = nl1.item(ⅰ);
                NL2 = node1.getChildNodes();

                节点locationNode = nl2.item(getNodeIndex(NL2的start_location));
                NL3 = locationNode.getChildNodes();
                节点latNode = nl3.item(getNodeIndex(NL3,纬度​​));
                双纬度= Double.parseDouble(latNode.getTextContent());
                节点lngNode = nl3.item(getNodeIndex(NL3,LNG));
                双LNG = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(新经纬度(纬度,经度));

                locationNode = nl2.item(getNodeIndex(NL2,折线));
                NL3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(NL3,分));
                ArrayList的<经纬度> ARR =去$ C $℃聚(latNode.getTextContent());
                对于(INT J = 0; J< arr.size(); J ++){
                    listGeopoints.add(新经纬度(arr.get(J).latitude,arr.get(J).longitude));
                }

                locationNode = nl2.item(getNodeIndex(NL2,END_LOCATION));
                NL3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(NL3,纬度​​));
                纬度= Double.parseDouble(latNode.getTextContent());
                lngNode = nl3.item(getNodeIndex(NL3,LNG));
                液化天然气= Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(新经纬度(纬度,经度));
            }
        }

        返回listGeopoints;
    }

    私人诠释getNodeIndex(节点列表NL,串节点名称){
        的for(int i = 0; I< nl.getLength();我++){
            如果(nl.item(我).getNodeName()。等于(节点名称))
                返回我;
        }
        返回-1;
    }

    私人的ArrayList<经纬度>德$ C $℃聚(字符串连接codeD){
        ArrayList的<经纬度>聚=新的ArrayList<经纬度>();
        INT指数= 0,len个= EN coded.length();
        INT纬度= 0,LNG = 0;
        而(指数< LEN){
            INT B,移= 0,结果为0;
            做 {
                B = EN coded.charAt(指数++) -  63;
                结果| =(B和0x1F的)LT;<转移;
                Shift + = 5;
            }而(B> = 0x20的);
            INT DLAT =((导致&安培; 1)= 0〜(结果>→1):!?(导致>→1));
            纬度+ = DLAT;
            移= 0;
            结果= 0;
            做 {
                B = EN coded.charAt(指数++) -  63;
                结果| =(B和0x1F的)LT;<转移;
                Shift + = 5;
            }而(B> = 0x20的);
            INT dlng =((导致&安培; 1)= 0〜(结果>→1):!?(导致>→1));
            LNG + = dlng;

            经纬度位置=新的经纬度((双)纬度/ 1E5,(双)LNG / 1E5);
            poly.add(位置);
        }
        返回聚;
    }
}
 

解决方案

我觉得你没有得到的谷歌服务器的响应,并解析它在文件 ,其他明智的你可以从转换的的InputStream 字符串使用:

 私人字符串convertStreamToString(最终的InputStream输入)抛出异常{
    尝试 {
        最后的BufferedReader读卡器=新的BufferedReader(新的InputStreamReader(输入));
        最后的StringBuffer SBUF =新的StringBuffer();
        串线= NULL;
        而((行= reader.readLine())!= NULL){
            sBuf.append(线);
        }
        返回sBuf.toString();
    }赶上(例外五){
        扔ê;
    } 最后 {
        尝试 {
            input.close();
        }赶上(例外五){
            扔ê;
        }
    }
 

那么你将不得不解析响应为JSONObject的

 的JSONObject的JSONObject =新的JSONObject(串);
 

那么你得到的 JSONArray 命名的路由

  JSONArray routeJSONArray = jSONObject.getJSONArray(路);
 

现在你就可以开始从JSONArray获得它的索引获取每个路由数据。

我已经写了code片段作为路线的典范

Route.java

 的Bean;
进口的java.util.ArrayList;
进口的java.util.List;

进口android.content.Context;

进口com.google.android.gms.maps.model.Polyline;

公共类路径实现Serializable {

    私有静态最后长的serialVersionUID = 1L;
    私人界界限;
    私人字符串著作权;
    私人列表<腿>双腿;
    私人折线overviewPolyLine;
    私人字符串摘要;

    大众路线(上下文的背景下){
        腿=新的ArrayList<腿>();
    }

    公共绑定的getBounds(){
        返回界限;
    }

    公共无效的setBounds(约束边界){
        this.bounds =界限;
    }

    公共字符串getCop​​yrights(){
        返回版权;
    }

    公共无效setCop​​yrights(字符串版权){
        this.copyrights =著作权;
    }

    公开名单<腿> getLegs(){
        返回的双腿;
    }

    公共无效setLegs(名单<腿>腿){
        this.legs =腿;
    }

    公共无效addLeg(腿腿){
        this.legs.add(腿);
    }

    公共折线getOverviewPolyLine(){
        返回overviewPolyLine;
    }

    公共无效setOverviewPolyLine(多义线overviewPolyLine){
        this.overviewPolyLine = overviewPolyLine;
    }

    公共字符串getSummary(){
        返回摘要;
    }

    公共无效setSummary(字符串摘要){
        this.summary =摘要;
    }

    公共静态长getSerialversionuid(){
        返回的serialVersionUID;
    }

}
 

Bound.java

 进口com.google.android.gms.maps.model.LatLng;

公共类绑定{
    私人经纬度东北部;
    私人经纬度西南;
    公共经纬度getNorthEast(){
        返回东北部;
    }
    公共无效setNorthEast(经纬度东北部){
        this.northEast =东北部;
    }
    公共经纬度getSouthWest(){
        返回西南;
    }
    公共无效setSouthWest(经纬度西南){
        this.southWest =西南;
    }
}
 

Leg.java

 进口的java.util.ArrayList;
进口的java.util.List;

进口com.google.android.gms.maps.model.LatLng;

公共类腿{
    私人距离距离;
    私人时间期限;
    私人字符串endAddress;
    私人经纬度EndLocation组件;
    私人字符串StartAddress开始;
    私人经纬度startLocation;
    私人列表<步骤>脚步;

    公共腿(){
        步骤=新的ArrayList&其中;工序>();
    }

    公共距离getDistance的(){
        返回的距离;
    }

    公共无效setDistance(距离距离){
        this.distance =距离;
    }

    公众持续时间getDuration(){
        返回时间;
    }

    公共无效setDuration(持续时间){
        this.duration =持续时间;
    }

    公共字符串getEndAddress(){
        返回endAddress;
    }

    公共无效setEndAddress(字符串endAddress){
        this.endAddress = endAddress;
    }

    公共经纬度getEndLocation(){
        返回EndLocation组件;
    }

    公共无效setEndLocation(经纬度EndLocation组件){
        this.endLocation = EndLocation组件;
    }

    公共字符串getStartAddress(){
        返回StartAddress开始;
    }

    公共无效setStartAddress(字符串StartAddress开始){
        this.startAddress = StartAddress开始;
    }

    公共经纬度getStartLocation(){
        返回startLocation;
    }

    公共无效setStartLocation(经纬度startLocation){
        this.startLocation = startLocation;
    }

    公开名单<步骤> getSteps(){
        返回步骤;
    }

    公共无效setSteps(名单<步骤>步骤){
        this.steps =步骤;
    }

    公共无效addStep(一步一步){
        this.steps.add(步骤);
    }

}
 

Distance.java

 公共类距离{
    私人字符串文本;
    私人长期价值;

    公众距离(字符串文本,长值){
        this.text =文本;
        THIS.VALUE =价值;
    }

    公共字符串的getText(){
        返回文本;
    }

    公共无效的setText(字符串文本){
        this.text =文本;
    }

    众长的getValue(){
        返回值;
    }

    公共无效的setValue(long值){
        THIS.VALUE =价值;
    }

}
 

Duration.java

 公共类持续时间{
    公众持续时间(字符串文本,长值){
        this.text =文本;
        THIS.VALUE =价值;
    }

    私人字符串文本;
    私人长期价值;

    公共字符串的getText(){
        返回文本;
    }

    公共无效的setText(字符串文本){
        this.text =文本;
    }

    众长的getValue(){
        返回值;
    }

    公共无效的setValue(long值){
        THIS.VALUE =价值;
    }

}
 

Step.java

 进口的java.util.List;

进口android.annotation.Sup pressLint;
进口android.content.Context;
进口android.graphics.drawable.Drawable;

进口com.google.android.gms.maps.model.LatLng;
进口com.nweave.etaxi.driver.R;

公共类步{
    私人距离距离;
    私人时间期限;
    私人经纬度EndLocation组件;
    私人经纬度startLocation;
    私人字符串htmlInstructions;
    私人字符串travelMode;
    私人列表<经纬度>分;

    公开名单<经纬度> getPoints(){
        返回点;
    }

    公共无效设定值(表<经纬度>分){
        this.points =分;
    }

    公共距离getDistance的(){
        返回的距离;
    }

    公共无效setDistance(距离距离){
        this.distance =距离;
    }

    公众持续时间getDuration(){
        返回时间;
    }

    公共无效setDuration(持续时间){
        this.duration =持续时间;
    }

    公共经纬度getEndLocation(){
        返回EndLocation组件;
    }

    公共无效setEndLocation(经纬度EndLocation组件){
        this.endLocation = EndLocation组件;
    }

    公共经纬度getStartLocation(){
        返回startLocation;
    }

    公共无效setStartLocation(经纬度startLocation){
        this.startLocation = startLocation;
    }

    公共字符串getHtmlInstructions(){
        返回htmlInstructions;
    }

    公共无效setHtmlInstructions(字符串htmlInstructions){
        this.htmlInstructions = htmlInstructions;
    }

    公共字符串getTravelMode(){
        返回travelMode;
    }

    公共无效setTravelMode(字符串travelMode){
        this.travelMode = travelMode;
    }
}
 

解析功能将

 公开名单<路线>解析(字符串routesJSONString)抛出异常{
    尝试 {
        名单<路线> routeList =新的ArrayList<路线>();
        最后的JSONObject的JSONObject =新的JSONObject(routesJSONString);
        JSONArray routeJSONArray = jSONObject.getJSONArray(ROUTES);
        路线路线;
        的JSONObject routesJSONObject;
        为(中间体米= 0; M&其中; routeJSONArray.length();米++){
            路线=新干线(上下文);
            routesJSONObject = routeJSONArray.getJSONObject(米);
            JSONArray legsJSONArray;
            route.setSummary(routesJSONObject.getString(摘要));
            legsJSONArray = routesJSONObject.getJSONArray(腿);
            的JSONObject legJSONObject;
            腿腿;
            JSONArray stepsJSONArray;
            为(中间体B = 0; b将legsJSONArray.length(),B ++){
                腿=新的腿();
                legJSONObject = legsJSONArray.getJSONObject(B);
                leg.setDistance(新距离(legJSONObject.optJSONObject(距离).optString(TEXT),legJSONObject.optJSONObject(距离).optLong(VALUE)));
                leg.setDuration(新的持续时间(legJSONObject.optJSONObject(持续时间).optString(TEXT),legJSONObject.optJSONObject(持续时间).optLong(VALUE)));
                stepsJSONArray = legJSONObject.getJSONArray(步骤);
                JSONObject的stepJSONObject,stepDurationJSONObject,legPolyLineJSONObject,stepStartLocationJSONObject,stepEndLocationJSONObject;
                一步一个脚印;
                字符串连接codedString;
                经纬度stepStartLocationLatLng,stepEndLocationLatLng;
                的for(int i = 0; I< stepsJSONArray.length();我++){
                    stepJSONObject = stepsJSONArray.getJSONObject(ⅰ);
                    步长=新步();
                    JSONObject的stepDistanceJSONObject = stepJSONObject.getJSONObject(距离);
                    step.setDistance(新距离(stepDistanceJSONObject.getString(TEXT),stepDistanceJSONObject.getLong(VALUE)));
                    stepDurationJSONObject = stepJSONObject.getJSONObject(持续时间);
                    step.setDuration(新的持续时间(stepDurationJSONObject.getString(TEXT),stepDurationJSONObject.getLong(VALUE)));
                    stepEndLocationJSONObject = stepJSONObject.getJSONObject(END_LOCATION);
                    stepEndLocationLatLng =新的经纬度(stepEndLocationJSONObject.getDouble(纬度),stepEndLocationJSONObject.getDouble(经度));
                    step.setEndLocation(stepEndLocationLatLng);
                    step.setHtmlInstructions(stepJSONObject.getString(HTML_INSTRUCTION));
                    legPolyLineJSONObject = stepJSONObject.getJSONObject(折线);
                    EN codedString = legPolyLineJSONObject.getString(分);
                    step.setPoints(德codePolyLines(EN codedString));
                    stepStartLocationJSONObject = stepJSONObject.getJSONObject(START_LOCATION);
                    stepStartLocationLatLng =新的经纬度(stepStartLocationJSONObject.getDouble(纬度),stepStartLocationJSONObject.getDouble(经度));
                    step.setStartLocation(stepStartLocationLatLng);
                    leg.addStep(步骤);
                }
                route.addLeg(腿);
            }
            routeList.add(路线);
        }
        返回routeList;
    }赶上(例外五){
        扔ê;
    }
 

关于步骤图片有一个HTML指令,并呼吁另一场机动其中,根据这个领域,你会选择你的形象

我希望这有助于;)

I am using this class to display a route on a map. The problem is that it only displays one route. What I want to do is display multiple alternate routes on the map. Even thought the server response has multiple routes, it only parses the first route and displays it. What changes should I make to display all the routes that the google server returns.Here is my class.

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

解决方案

i think you don't have to get the response of Google Server and parse it in Document, other wise you can convert from InputStream to String using:

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

then you will have to parse the response as JSONObject

JSONObject jSONObject = new JSONObject(string);

then you get JSONArray named routes

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

now you can start fetching data from each route by getting its index from JSONArray.

i have written a snippet of code as a model of route

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

the parsing function will be

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

Regarding the Step Image there is an HTML instruction and another field called maneuver where according to this field you will choose your image

i hope this helps ;)

这篇关于显示使用方向API在Android的多条路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆