如何使用突出显示的最短路径编码从源到目的地的多种可能路线

时间:2015-11-30 12:18:27

标签: java android google-maps

我已经映射了一条从源到目的地的可能路线,现在我想知道如何使用突出显示的最短路径编码从源到目的地的多条可能路线, 我试过的代码如下,

MainActivity.java

public class MainActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMyLocationChangeListener {

GoogleMap mGoogleMap;
ArrayList<LatLng> mMarkerPoints;
double mLatitude = 0;
double mLongitude = 0;
SupportMapFragment supportMapFragment;
int i = 0;
String loopValue = "";
TextView textView;
Location mLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView =(TextView)findViewById(R.id.txt_loop);
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.frg_map);
    mapFragment.getMapAsync(this);
    mMarkerPoints = new ArrayList<LatLng>();
}
@Override
public void onMapReady(GoogleMap googleMap) {
    Log.d(getClass().getSimpleName(), "Map Ready");
    if(googleMap != null)
      mGoogleMap = googleMap;
    googleMap.setMyLocationEnabled(true);
    googleMap.setOnMyLocationChangeListener(this);
    googleMap.getUiSettings().setMyLocationButtonEnabled(true);
    mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                mGoogleMap.clear();
                    LatLng source = mMarkerPoints.get(0);
                    LatLng destination = latLng;

                    String url = getDirectionsUrl(source, destination);

                    DownloadTask downloadTask = new DownloadTask();
                    downloadTask.execute(url);
                drawMarker(mMarkerPoints.get(0));
                drawMarker(latLng);

            }
        });


}

private String getDirectionsUrl(LatLng source, LatLng destination) {

    String mSource = "origin=" + source.latitude + "," + source.longitude;
    String mDestination = "destination=" + destination.latitude + "," + destination.longitude;
    String mSensor = "sensor=false";
    String mParameters = mSource + "&" + mDestination + "&" + mSensor;
    String mOutput = "json";
    String murl = "https://maps.googleapis.com/maps/api/directions/" + mOutput + "?" + mParameters;
    return murl;
}

private String downloadUrl(String mUrl) throws IOException {
    String mdata = "";
    InputStream inputStream = null;
    HttpURLConnection httpURLConnection = null;

    try {
        URL url = new URL(mUrl);
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.connect();
        inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuffer stringBuffer = new StringBuffer();
        String mLine = "";
        while ((mLine = bufferedReader.readLine()) != null) {
            stringBuffer.append(mLine);
        }
        mdata = stringBuffer.toString();
        bufferedReader.close();
    } catch (Exception e) {
        Log.d("Exception While downloading url", e.toString());
    } finally {
        inputStream.close();
        httpURLConnection.disconnect();
    }
    return mdata;
}

@Override
public void onMyLocationChange(Location location) {
    if (mLocation == null) {
        mLocation = location;
        mLatitude = location.getLatitude();
        mLongitude = location.getLongitude();
        LatLng point = new LatLng(mLatitude, mLongitude);
        mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(point, 15));
        drawMarker(point);
        loopValue = "Loop : "+ i +" "+ mMarkerPoints.size()+"\n";
        textView.setText(loopValue);
        i++;
    }
}

private class DownloadTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... url) {
        String mData = "";
        try {
            mData = downloadUrl(url[0]);
        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        Log.d("Background Task", mData);
        return mData;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        ParserTask parserTask = new ParserTask();
        parserTask.execute(result);
    }
}

private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>> > {

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

        JSONObject jObject;
        List<List<HashMap<String, String>>> routes = new ArrayList<>();

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

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        Log.d(getClass().getSimpleName(), "Result: "+result.toArray().toString()+" Result size: "+result.size());
        ArrayList<LatLng> points = null;
        PolylineOptions lineOptions = null;

        for (int i = 0; i < result.size(); i++) {
            Log.d(getClass().getSimpleName(), "Loop: "+i);
            points = new ArrayList<LatLng>();

            lineOptions = new PolylineOptions();

            List<HashMap<String, String>> path = result.get(i);

            for (int j = 0; j < path.size(); j++) {
                Log.d(getClass().getSimpleName(), "Loop inner: "+j);
                HashMap<String, String> latLngss = path.get(j);

                double lat = Double.parseDouble(latLngss.get("lat"));
                double lng = Double.parseDouble(latLngss.get("lng"));
                LatLng position = new LatLng(lat, lng);
                Log.d(getClass().getSimpleName(), "Hash : " + latLngss.toString());
                points.add(position);
            }
        }
        mGoogleMap.addPolyline(new PolylineOptions()
                .addAll(points)
                .width(5)
                .color(Color.RED));
    }
}

@Override
public boolean onCreateOptionsMenu (Menu menu){
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;

}

private void drawMarker(LatLng point) {
    mMarkerPoints.add(point);
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(point);

    if (mMarkerPoints.size() == 1) {
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
    } else if (mMarkerPoints.size() == 2) {
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
    }
    mGoogleMap.addMarker(markerOptions);
} }

DirectionsJSONParser.java

public class DirectionsJSONParser {

public List<List<HashMap<String,String>>> parse(JSONObject jObject){

    List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
    JSONArray jRoutes = null;
    JSONArray jLegs = null;
    JSONArray jSteps = null;

    try {

        jRoutes = jObject.getJSONArray("routes");
        for(int i=0;i<jRoutes.length();i++){
            jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
            List path = new ArrayList<HashMap<String, String>>();
            for(int j=0;j<jLegs.length();j++){
                jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
                for(int k=0;k<jSteps.length();k++){
                    String polyline = "";
                    polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
                    List<LatLng> list = decodePoly(polyline);
                    for(int l=0;l<list.size();l++){
                        HashMap<String, String> hm = new HashMap<String, String>();
                        hm.put("lat", Double.toString(list.get(l).latitude) );
                        hm.put("lng", Double.toString(list.get(l).longitude) );
                        path.add(hm);
                    }
                }
                routes.add(path);
            }
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }catch (Exception e){
    }
    return routes;
}
private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

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

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

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

1 个答案:

答案 0 :(得分:0)

我还制作了Google地图应用。 我有很多MTB(山地自行车)小径,我决定做 Polyline 这是我的代码的一部分:

  Polyline line = mapa.addPolyline(new PolylineOptions()
            .add(new LatLng(43.38, -5.849),
                    new LatLng(nextCoord),
                    new LatLng(nextCoord),
                    new LatLng(nextCoord))
                   .width(10)
                   .color(Color.GREEN));

因此,您将标记“路径”。