2014-12-05 108 views
2

我可以在android地图v2上的两个地理点之间使用多段线绘制单一路线。但我不知道如何绘制从源到目的地的多条路线我试图添加“alternatives = true”,但仍然只能在地图上获得一条路线。有人请帮助我如何做到这一点,因为我在网上做了很多研究,但仍然无法找到任何容易理解的解决方案。Android:如何在地图上绘制从源到目的地的多条路线?

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


    } 
    }); 

回答

2

您需要使用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; 
    } 
} 

有关详细信息,请参阅here

相关问题