Android:如何在地图上绘制从源到目的地的多条路线?

用户名

我能够在Android地图v2的两个地理位置之间使用折线绘制一条路线。但是我不知道如何绘制从源到目的地的多条路线,我试图添加“ alternatives = true”,但在地图上仍然只能获得一条路线。有人请帮我解决这个问题,因为我在网络上进行了大量研究,但仍然找不到任何易于理解的解决方案。

GoogleDirection.java

@SuppressLint("NewApi")
public class GoogleDirection {


public GoogleDirection(Context context) { 
    mContext = context;
}


public String request(LatLng start, LatLng end, String mode) {
    final 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";

    if(isLogging)
        Log.i("GoogleDirection", "URL : " + url);
    new RequestTask().execute(new String[]{ url });
    return url;
}

private class RequestTask extends AsyncTask<String, Void, Document> {
    protected Document doInBackground(String... url) {
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(url[0]);
            HttpResponse response = httpClient.execute(httpPost, localContext);
            InputStream in = response.getEntity().getContent();
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            return builder.parse(in);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } 
        return null;
    }

    protected void onPostExecute(Document doc) {
        super.onPostExecute(doc);
        if(mDirectionListener != null)
            mDirectionListener.onResponse(getStatus(doc), doc, GoogleDirection.this);
    }

    private String getStatus(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("status");
        Node node1 = nl1.item(0);
        if(isLogging)
            Log.i("GoogleDirection", "Status : " + node1.getTextContent());
        return node1.getTextContent();
    }
}

public void setLogging(boolean state) {
    isLogging = state;
}

public String getStatus(Document doc) {
    NodeList nl1 = doc.getElementsByTagName("status");
    Node node1 = nl1.item(0);
    if(isLogging)
        Log.i("GoogleDirection", "Status : " + node1.getTextContent());
    return node1.getTextContent();
}

public String[] getDurationText(Document doc) {
    NodeList nl1 = doc.getElementsByTagName("duration");
    String[] arr_str = new String[nl1.getLength() - 1];
    for(int i = 0 ; i < nl1.getLength() - 1 ; i++) {
        Node node1 = nl1.item(i);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
        arr_str[i] = node2.getTextContent();
        if(isLogging)
            Log.i("GoogleDirection", "DurationText : " + node2.getTextContent());
    }
    return arr_str;
}

public int[] getDurationValue(Document doc) {
    NodeList nl1 = doc.getElementsByTagName("duration");
    int[] arr_int = new int[nl1.getLength() - 1];
    for(int i = 0 ; i < nl1.getLength() - 1 ; i++) {
        Node node1 = nl1.item(i);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));
        arr_int[i] = Integer.parseInt(node2.getTextContent());
        if(isLogging)
            Log.i("GoogleDirection", "Duration : " + node2.getTextContent());
    }
    return arr_int;
}

public String getTotalDurationText(Document doc) {
    NodeList nl1 = doc.getElementsByTagName("duration");
    Node node1 = nl1.item(nl1.getLength() - 1);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = nl2.item(getNodeIndex(nl2, "text"));
    if(isLogging)
        Log.i("GoogleDirection", "TotalDuration : " + node2.getTextContent());
    return node2.getTextContent();
}

public int getTotalDurationValue(Document doc) {
    NodeList nl1 = doc.getElementsByTagName("duration");
    Node node1 = nl1.item(nl1.getLength() - 1);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = nl2.item(getNodeIndex(nl2, "value"));
    if(isLogging)
        Log.i("GoogleDirection", "TotalDuration : " + node2.getTextContent());
    return Integer.parseInt(node2.getTextContent());
}

public String[] getDistanceText(Document doc) {
    NodeList nl1 = doc.getElementsByTagName("distance");
    String[] arr_str = new String[nl1.getLength() - 1];
    for(int i = 0 ; i < nl1.getLength() - 1 ; i++) {
        Node node1 = nl1.item(i);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
        arr_str[i] = node2.getTextContent();
        if(isLogging)
            Log.i("GoogleDirection", "DurationText : " + node2.getTextContent());
    }
    return arr_str;
}

public int[] getDistanceValue(Document doc) {
    NodeList nl1 = doc.getElementsByTagName("distance");
    int[] arr_int = new int[nl1.getLength() - 1];
    for(int i = 0 ; i < nl1.getLength() - 1 ; i++) {
        Node node1 = nl1.item(i);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));
        arr_int[i] = Integer.parseInt(node2.getTextContent());
        if(isLogging)
            Log.i("GoogleDirection", "Duration : " + node2.getTextContent());
    }
    return arr_int;
}

public String getTotalDistanceText(Document doc) {
    NodeList nl1 = doc.getElementsByTagName("distance");
    Node node1 = nl1.item(nl1.getLength() - 1);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = nl2.item(getNodeIndex(nl2, "text"));
    if(isLogging)
        Log.i("GoogleDirection", "TotalDuration : " + node2.getTextContent());
    return node2.getTextContent();
}

public int getTotalDistanceValue(Document doc) {
    NodeList nl1 = doc.getElementsByTagName("distance");
    Node node1 = nl1.item(nl1.getLength() - 1);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = nl2.item(getNodeIndex(nl2, "value"));
    if(isLogging)
        Log.i("GoogleDirection", "TotalDuration : " + node2.getTextContent());
    return Integer.parseInt(node2.getTextContent());
}

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

public String getEndAddress(Document doc) {
    NodeList nl1 = doc.getElementsByTagName("end_address");
    Node node1 = nl1.item(0);
    if(isLogging)
        Log.i("GoogleDirection", "StartAddress : " + node1.getTextContent());
    return node1.getTextContent();
}

public String getCopyRights(Document doc) {
    NodeList nl1 = doc.getElementsByTagName("copyrights");
    Node node1 = nl1.item(0);
    if(isLogging)
        Log.i("GoogleDirection", "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;
}

public ArrayList<LatLng> getSection(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, "end_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));
        }
    }

    return listGeopoints;
}

public PolylineOptions getPolyline(Document doc, int width, int color) {
    ArrayList<LatLng> arr_pos = getDirection(doc);
    PolylineOptions rectLine = new PolylineOptions().width(dpToPx(width)).color(color);
    for(int i = 0 ; i < arr_pos.size() ; i++)        
        rectLine.add(arr_pos.get(i));
    return rectLine;
}

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

private int dpToPx(int dp) {
    DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
    int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));       
    return px;
}

public void setOnDirectionResponseListener(OnDirectionResponseListener listener) {
    mDirectionListener = listener;
}

public void setOnAnimateListener(OnAnimateListener listener) {
    mAnimateListener = listener;
}

public interface OnDirectionResponseListener {
    public void onResponse(String status, Document doc, GoogleDirection gd);
}

public interface OnAnimateListener {
    public void onFinish();
    public void onStart();
    public void onProgress(int progress, int total);
}

public void animateDirection(GoogleMap gm, ArrayList<LatLng> direction, int speed
        , boolean cameraLock, boolean isCameraTilt, boolean isCameraZoom
        , boolean drawMarker, MarkerOptions mo, boolean flatMarker
        , boolean drawLine, PolylineOptions po) {
    if(direction.size() > 1) {
        isAnimated = true;
        animatePositionList = direction;
        animateSpeed = speed;
        this.drawMarker = drawMarker;
        this.drawLine = drawLine;
        this.flatMarker = flatMarker;
        this.isCameraTilt = isCameraTilt;
        this.isCameraZoom = isCameraZoom;
        step = 0;
        this.cameraLock = cameraLock;
        this.gm = gm;

        setCameraUpdateSpeed(speed);

        beginPosition = animatePositionList.get(step);
        endPosition = animatePositionList.get(step + 1);
        animateMarkerPosition = beginPosition;

        if(mAnimateListener != null)
            mAnimateListener.onProgress(step, animatePositionList.size());

        if(cameraLock) {
            float bearing = getBearing(beginPosition, endPosition);
            CameraPosition.Builder cameraBuilder = new CameraPosition.Builder()
                .target(animateMarkerPosition).bearing(bearing);

            if(isCameraTilt) 
                cameraBuilder.tilt(90);
            else 
                cameraBuilder.tilt(gm.getCameraPosition().tilt);

            if(isCameraZoom) 
                cameraBuilder.zoom(zoom);
            else 
                cameraBuilder.zoom(gm.getCameraPosition().zoom);

            CameraPosition cameraPosition = cameraBuilder.build();
            gm.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
        }

        if(drawMarker) {
            if(mo != null)
                animateMarker = gm.addMarker(mo.position(beginPosition));
            else 
                animateMarker = gm.addMarker(new MarkerOptions().position(beginPosition));

            if(flatMarker) {
                animateMarker.setFlat(true);

                float rotation = getBearing(animateMarkerPosition, endPosition) + 180;
                animateMarker.setRotation(rotation);
            }
        }


        if(drawLine) {
            if(po != null) 
                animateLine = gm.addPolyline(po.add(beginPosition)
                        .add(beginPosition).add(endPosition)
                        .width(dpToPx((int)po.getWidth())));
            else 
                animateLine = gm.addPolyline(new PolylineOptions()
                        .width(dpToPx(5)));
        }

        new Handler().postDelayed(r, speed);
        if(mAnimateListener != null)
            mAnimateListener.onStart();
    }
}

public void cancelAnimated() {
    isAnimated = false;
}

public boolean isAnimated() {
    return isAnimated;
}

private Runnable r = new Runnable() {
    public void run() {

        animateMarkerPosition = getNewPosition(animateMarkerPosition, endPosition);

        if(drawMarker)
            animateMarker.setPosition(animateMarkerPosition);


        if(drawLine) {
            List<LatLng> points = animateLine.getPoints();
            points.add(animateMarkerPosition);
            animateLine.setPoints(points);
        }

        if((animateMarkerPosition.latitude == endPosition.latitude 
                && animateMarkerPosition.longitude == endPosition.longitude)) {
            if(step == animatePositionList.size() - 2) {
                isAnimated = false;
                totalAnimateDistance = 0;
                if(mAnimateListener != null)
                    mAnimateListener.onFinish();
            } else {
                step++;
                beginPosition = animatePositionList.get(step);
                endPosition = animatePositionList.get(step + 1);
                animateMarkerPosition = beginPosition;

                if(flatMarker && step + 3 < animatePositionList.size() - 1) {
                    float rotation = getBearing(animateMarkerPosition, animatePositionList.get(step + 3)) + 180;
                    animateMarker.setRotation(rotation);
                }

                if(mAnimateListener != null)
                    mAnimateListener.onProgress(step, animatePositionList.size());
            }
        }

        if(cameraLock && (totalAnimateDistance > animateCamera || !isAnimated)) {
            totalAnimateDistance = 0;
            float bearing = getBearing(beginPosition, endPosition);
            CameraPosition.Builder cameraBuilder = new CameraPosition.Builder()
                .target(animateMarkerPosition).bearing(bearing);

            if(isCameraTilt) 
                cameraBuilder.tilt(90);
            else 
                cameraBuilder.tilt(gm.getCameraPosition().tilt);

            if(isCameraZoom) 
                cameraBuilder.zoom(zoom);
            else 
                cameraBuilder.zoom(gm.getCameraPosition().zoom);

            CameraPosition cameraPosition = cameraBuilder.build();
            gm.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        }

        if(isAnimated) {
            new Handler().postDelayed(r, animateSpeed);
        }
    }
};

public Marker getAnimateMarker() {
    return animateMarker;
}

public Polyline getAnimatePolyline() {
    return animateLine;
}

private LatLng getNewPosition(LatLng begin, LatLng end) {
    double lat = Math.abs(begin.latitude - end.latitude); 
    double lng = Math.abs(begin.longitude - end.longitude);

    double dis = Math.sqrt(Math.pow(lat, 2) + Math.pow(lng, 2));
    if(dis >= animateDistance) {
        double angle = -1;

        if(begin.latitude <= end.latitude && begin.longitude <= end.longitude)
            angle = Math.toDegrees(Math.atan(lng / lat));
        else if(begin.latitude > end.latitude && begin.longitude <= end.longitude)
            angle = (90 - Math.toDegrees(Math.atan(lng / lat))) + 90;
        else if(begin.latitude > end.latitude && begin.longitude > end.longitude)
            angle = Math.toDegrees(Math.atan(lng / lat)) + 180;
        else if(begin.latitude <= end.latitude && begin.longitude > end.longitude)
            angle = (90 - Math.toDegrees(Math.atan(lng / lat))) + 270;

        double x = Math.cos(Math.toRadians(angle)) * animateDistance;
        double y = Math.sin(Math.toRadians(angle)) * animateDistance;
        totalAnimateDistance += animateDistance;
        double finalLat = begin.latitude + x;
        double finalLng = begin.longitude + y;

        return new LatLng(finalLat, finalLng);
    } else {
        return end;
    }
}

private float getBearing(LatLng begin, LatLng end) {
    double lat = Math.abs(begin.latitude - end.latitude); 
    double lng = Math.abs(begin.longitude - end.longitude);
     if(begin.latitude < end.latitude && begin.longitude < end.longitude)
        return (float)(Math.toDegrees(Math.atan(lng / lat)));
    else if(begin.latitude >= end.latitude && begin.longitude < end.longitude)
        return (float)((90 - Math.toDegrees(Math.atan(lng / lat))) + 90);
    else if(begin.latitude >= end.latitude && begin.longitude >= end.longitude)
        return  (float)(Math.toDegrees(Math.atan(lng / lat)) + 180);
    else if(begin.latitude < end.latitude && begin.longitude >= end.longitude)
        return (float)((90 - Math.toDegrees(Math.atan(lng / lat))) + 270);
     return -1;
}

public void setCameraUpdateSpeed(int speed) {       
    if(speed == SPEED_VERY_SLOW) {
        animateDistance = 0.000005;
        animateSpeed = 20;
        animateCamera = 0.0004;
        zoom = 19;
    } else if(speed == SPEED_SLOW) {
        animateDistance = 0.00001;
        animateSpeed = 20;
        animateCamera = 0.0008;
        zoom = 18;
    } else if(speed == SPEED_NORMAL) {
        animateDistance = 0.00005;
        animateSpeed = 20;
        animateCamera = 0.002;
        zoom = 16;
    } else if(speed == SPEED_FAST) {
        animateDistance = 0.0001;
        animateSpeed = 20;
        animateCamera = 0.004;
        zoom = 15;
    } else if(speed == SPEED_VERY_FAST) {
        animateDistance = 0.0005;
        animateSpeed = 20;
        animateCamera = 0.004;
        zoom = 13;
    } else {
        animateDistance = 0.00005;
        animateSpeed = 20;
        animateCamera = 0.002;
        zoom = 16;
    }
}
}

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);


    gd = new GoogleDirection(this);
    gd.setOnDirectionResponseListener(new OnDirectionResponseListener() {
        public void onResponse(String status, Document doc, GoogleDirection gd) {
            mDoc = doc;
        polyline =  mGoogleMap.addPolyline(gd.getPolyline(doc, 10, Color.RED)); 

          }
    });

route.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View view) {
            // TODO Auto-generated method stub


            LatLng newLatLong1 = new LatLng(la1d, lo1d);
            LatLng newLatLong2 = new LatLng(la2d, lo2d);

            gd.setLogging(true);
            gd.request(newLatLong2, newLatLong1, GoogleDirection.MODE_DRIVING);


    }
    });
bjiang

您需要使用Google Directions API只需使用HTTP请求命中给定的URL并获取json响应。此Google服务会计算给定位置之间的方向。

样例代码:

PathGoogleMapActivity.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

public class PathGoogleMapActivity extends FragmentActivity {

    private static final LatLng LOWER_MANHATTAN = new LatLng(40.722543,
            -73.998585);
    private static final LatLng BROOKLYN_BRIDGE = new LatLng(40.7057, -73.9964);
    private static final LatLng WALL_STREET = new LatLng(40.7064, -74.0094);

    GoogleMap googleMap;
    final String TAG = "PathGoogleMapActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_path_google_map);
        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        googleMap = fm.getMap();

        MarkerOptions options = new MarkerOptions();
        options.position(LOWER_MANHATTAN);
        options.position(BROOKLYN_BRIDGE);
        options.position(WALL_STREET);
        googleMap.addMarker(options);
        String url = getMapsApiDirectionsUrl();
        ReadTask downloadTask = new ReadTask();
        downloadTask.execute(url);

        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(BROOKLYN_BRIDGE,
                13));
        addMarkers();

    }

    private String getMapsApiDirectionsUrl() {
        String waypoints = "waypoints=optimize:true|"
                + LOWER_MANHATTAN.latitude + "," + LOWER_MANHATTAN.longitude
                + "|" + "|" + BROOKLYN_BRIDGE.latitude + ","
                + BROOKLYN_BRIDGE.longitude + "|" + WALL_STREET.latitude + ","
                + WALL_STREET.longitude;

        String sensor = "sensor=false";
        String params = waypoints + "&" + sensor;
        String output = "json";
        String url = "https://maps.googleapis.com/maps/api/directions/"
                + output + "?" + params;
        return url;
    }

    private void addMarkers() {
        if (googleMap != null) {
            googleMap.addMarker(new MarkerOptions().position(BROOKLYN_BRIDGE)
                    .title("First Point"));
            googleMap.addMarker(new MarkerOptions().position(LOWER_MANHATTAN)
                    .title("Second Point"));
            googleMap.addMarker(new MarkerOptions().position(WALL_STREET)
                    .title("Third Point"));
        }
    }

    private class ReadTask extends AsyncTask {
        @Override
        protected String doInBackground(String... url) {
            String data = "";
            try {
                HttpConnection http = new HttpConnection();
                data = http.readUrl(url[0]);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }

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

    private class ParserTask extends
            AsyncTask>>> {

        @Override
        protected List>> doInBackground(
                String... jsonData) {

            JSONObject jObject;
            List>> routes = null;

            try {
                jObject = new JSONObject(jsonData[0]);
                PathJSONParser parser = new PathJSONParser();
                routes = parser.parse(jObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return routes;
        }

        @Override
        protected void onPostExecute(List>> routes) {
            ArrayList points = null;
            PolylineOptions polyLineOptions = null;

            // traversing through routes
            for (int i = 0; i < routes.size(); i++) {
                points = new ArrayList();
                polyLineOptions = new PolylineOptions();
                List> path = routes.get(i);

                for (int j = 0; j < path.size(); j++) {
                    HashMap 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);
                }

                polyLineOptions.addAll(points);
                polyLineOptions.width(2);
                polyLineOptions.color(Color.BLUE);
            }

            googleMap.addPolyline(polyLineOptions);
        }
    }
}

HttpConnection.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.util.Log;

public class HttpConnection {
    public String readUrl(String mapsApiDirectionsUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(mapsApiDirectionsUrl);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            iStream = urlConnection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    iStream));
            StringBuffer sb = new StringBuffer();
            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            data = sb.toString();
            br.close();
        } catch (Exception e) {
            Log.d("Exception while reading url", e.toString());
        } finally {
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

}

PathJSONParser.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gms.maps.model.LatLng;

public class PathJSONParser {

    public List>> parse(JSONObject jObject) {
        List>> routes = new ArrayList>>();
        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>();

                /** Traversing all legs */
                for (int j = 0; j < jLegs.length(); j++) {
                    jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                    /** 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 list = decodePoly(polyline);

                        /** Traversing all points */
                        for (int l = 0; l < list.size(); l++) {
                            HashMap hm = new HashMap();
                            hm.put("lat",
                                    Double.toString(((LatLng) list.get(l)).latitude));
                            hm.put("lng",
                                    Double.toString(((LatLng) list.get(l)).longitude));
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
        }
        return routes;
    }

    /**
     * Method Courtesy :
     * jeffreysambells.com/2010/05/27
     * /decoding-polylines-from-google-maps-direction-api-with-java
     * */
    private List decodePoly(String encoded) {

        List poly = new ArrayList();
        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;
    }
}

有关更多详细信息,请参阅此处

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Android:如何在地图上绘制从源到目的地的多条路线?

来自分类Dev

如何在Android中显示从当前位置到固定目的地的路线

来自分类Dev

如何在地图上删除绘制路线

来自分类Dev

在iOS App中绘制用户当前位置到目的地之间的路线方向?

来自分类Dev

Android如何在地图上绘制圆圈

来自分类Dev

如何将 redis 流量从单个源复制到多个目的地

来自分类Dev

如何将变量传递到谷歌地图的目的地

来自分类Dev

单击目的地后创建从起点到目的地地图标记的路线线(驾驶)

来自分类Dev

如何通过不同的路线获取从源位置到目的地位置的所有经度和纬度

来自分类Dev

如何在Android的Google地图上绘制自由手形

来自分类Dev

如何计算源和目的地之间的跳数?

来自分类Dev

使用Google Map API v2在android中绘制从当前位置到目的地位置的路线

来自分类Dev

在无目的地的Google地图上获得x公里后的纬度经度?

来自分类Dev

此处绘制的路线图考虑了目的地必须位于街道的哪一边

来自分类Dev

如何使用JavaScript API在Arcgis地图上绘制路线?

来自分类Dev

如何借助经纬度在谷歌地图上绘制路线?

来自分类Dev

在Google地图上绘制多条折线

来自分类Dev

如何在栅格地图上绘制值?

来自分类Dev

如何在ggplot2地图上绘制条形图

来自分类Dev

如何在Android应用程序上更改文件下载目的地

来自分类Dev

如何在SwiftUI中更改NavigationView的目的地?

来自分类Dev

使用MKPolyline在地图上绘制用户路线

来自分类Dev

使用MKPolyline在地图上绘制用户路线

来自分类Dev

如何在地图上显示特定路线的实时路况数据

来自分类Dev

如何在NetLogo中到目的地的网络加权路径上找到下一个海龟?

来自分类Dev

如何在我的地图上提交路线叠加,然后在地图上看到它?

来自分类Dev

如何使用googlemap javascript api在1张地图中绘制多条公交路线

来自分类Dev

如何在Android的Google地图上绘制动态旅行路径

来自分类Dev

如何在android中通过json数组在谷歌地图上绘制折线?

Related 相关文章

  1. 1

    Android:如何在地图上绘制从源到目的地的多条路线?

  2. 2

    如何在Android中显示从当前位置到固定目的地的路线

  3. 3

    如何在地图上删除绘制路线

  4. 4

    在iOS App中绘制用户当前位置到目的地之间的路线方向?

  5. 5

    Android如何在地图上绘制圆圈

  6. 6

    如何将 redis 流量从单个源复制到多个目的地

  7. 7

    如何将变量传递到谷歌地图的目的地

  8. 8

    单击目的地后创建从起点到目的地地图标记的路线线(驾驶)

  9. 9

    如何通过不同的路线获取从源位置到目的地位置的所有经度和纬度

  10. 10

    如何在Android的Google地图上绘制自由手形

  11. 11

    如何计算源和目的地之间的跳数?

  12. 12

    使用Google Map API v2在android中绘制从当前位置到目的地位置的路线

  13. 13

    在无目的地的Google地图上获得x公里后的纬度经度?

  14. 14

    此处绘制的路线图考虑了目的地必须位于街道的哪一边

  15. 15

    如何使用JavaScript API在Arcgis地图上绘制路线?

  16. 16

    如何借助经纬度在谷歌地图上绘制路线?

  17. 17

    在Google地图上绘制多条折线

  18. 18

    如何在栅格地图上绘制值?

  19. 19

    如何在ggplot2地图上绘制条形图

  20. 20

    如何在Android应用程序上更改文件下载目的地

  21. 21

    如何在SwiftUI中更改NavigationView的目的地?

  22. 22

    使用MKPolyline在地图上绘制用户路线

  23. 23

    使用MKPolyline在地图上绘制用户路线

  24. 24

    如何在地图上显示特定路线的实时路况数据

  25. 25

    如何在NetLogo中到目的地的网络加权路径上找到下一个海龟?

  26. 26

    如何在我的地图上提交路线叠加,然后在地图上看到它?

  27. 27

    如何使用googlemap javascript api在1张地图中绘制多条公交路线

  28. 28

    如何在Android的Google地图上绘制动态旅行路径

  29. 29

    如何在android中通过json数组在谷歌地图上绘制折线?

热门标签

归档