Android谷歌地图方向api-关于路线

时间:2018-01-12 04:18:31

标签: android google-maps google-maps-direction-api

我的应用正在使用Google Maps Direction api,它可以显示起点和目的地之间的路线。但是,我认为这条路线不是指导一个人的最简单方式。该路线提供了复杂且更耗时的方向。例如,这两个地方可以通过直线路线连接,但是api给了我一条穿过其他地方的长路线。它是正常的还是代码中可以改进的东西? 这是我的代码:

MapsActivity:

   private void sendRequest() {

    mDatabase.child("users").child(user.getUid()).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
                latitude = dataSnapshot.child("latitude").getValue(Double.class);
                longitude = dataSnapshot.child("longitude").getValue(Double.class);
                destination = dataSnapshot.child("Address").getValue(String.class);
                origin = getCompleteAddressString(latitude, longitude);
            ((TextView) findViewById(R.id.textView6)).setText(origin);
            ((TextView) findViewById(R.id.textView7)).setText(destination);
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
    origin=((TextView) findViewById(R.id.textView6)).getText().toString();
    destination=((TextView) findViewById(R.id.textView7)).getText().toString();

            try{
                new DirectionFinder(this,origin,destination).execute();
            } catch(UnsupportedEncodingException e)
            {
                e.printStackTrace();
            }

}




private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
    String strAdd = "";
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
        if (addresses != null) {
            Address returnedAddress = addresses.get(0);
            StringBuilder strReturnedAddress = new StringBuilder("");

            for (int i = 0; i <= returnedAddress.getMaxAddressLineIndex(); i++) {
                strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
            }
            strAdd = strReturnedAddress.toString();
            Log.w("", strReturnedAddress.toString());
        } else {
            Log.w("", "No Address returned!");
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.w("", "Canont get Address!");
    }
    return strAdd;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    LatLng hcmus = new LatLng(22.316377, 114.180330);
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(hcmus, 18));
    originMarkers.add(mMap.addMarker(new MarkerOptions()
            .title("Find Direction")
            .position(hcmus)));

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    mMap.setMyLocationEnabled(true);
}


@Override
public void onDirectionFinderStart() {
    progressDialog = ProgressDialog.show(this, "Please wait.",
            "Finding direction..!", true);

    if (originMarkers != null) {
        for (Marker marker : originMarkers) {
            marker.remove();
        }
    }

    if (destinationMarkers != null) {
        for (Marker marker : destinationMarkers) {
            marker.remove();
        }
    }

    if (polylinePaths != null) {
        for (Polyline polyline : polylinePaths) {
            polyline.remove();
        }
    }
}

@Override
public void onDirectionFinderSuccess(List<Route> routes) {
    progressDialog.dismiss();
    polylinePaths = new ArrayList<>();
    originMarkers = new ArrayList<>();
    destinationMarkers = new ArrayList<>();

    for (Route route : routes) {
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 16));
        ((TextView) findViewById(R.id.tvDuration)).setText(route.duration.text);
        ((TextView) findViewById(R.id.tvDistance)).setText(route.distance.text);

        originMarkers.add(mMap.addMarker(new MarkerOptions()
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.start_blue))
                .title(route.startAddress)
                .position(route.startLocation)));
        destinationMarkers.add(mMap.addMarker(new MarkerOptions()
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green))
                .title(route.endAddress)
                .position(route.endLocation)));

        PolylineOptions polylineOptions = new PolylineOptions().
                geodesic(true).
                color(Color.BLUE).
                width(10);

        for (int i = 0; i < route.points.size(); i++)
            polylineOptions.add(route.points.get(i));

        polylinePaths.add(mMap.addPolyline(polylineOptions));
    }
}
}

DirectionFinder:

public class DirectionFinder {
private static final String DIRECTION_URL_API = "https://maps.googleapis.com/maps/api/directions/json?";
private static final String GOOGLE_API_KEY = "AIzaSyBa2FPukpJpwZTM-F6rjdGhIXB8vkcCcog";
private DirectionFinderListener listener;
private String origin;
private String destination;

public DirectionFinder(DirectionFinderListener listener, String origin, String destination) {
    this.listener = listener;
    this.origin = origin;
    this.destination = destination;
}

public void execute() throws UnsupportedEncodingException {
    listener.onDirectionFinderStart();
    new DownloadRawData().execute(createUrl());
}

private String createUrl() throws UnsupportedEncodingException {
    String urlOrigin = URLEncoder.encode(origin, "utf-8");
    String urlDestination = URLEncoder.encode(destination, "utf-8");

    return DIRECTION_URL_API + "origin=" + urlOrigin + "&destination=" + urlDestination + "&key=" + GOOGLE_API_KEY;
}

private class DownloadRawData extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        String link = params[0];
        try {
            URL url = new URL(link);
            InputStream is = url.openConnection().getInputStream();
            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));

            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line + "\n");
            }

            return buffer.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String res) {
        try {
            parseJSon(res);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

private void parseJSon(String data) throws JSONException {
    if (data == null)
        return;

    List<Route> routes = new ArrayList<Route>();
    JSONObject jsonData = new JSONObject(data);
    JSONArray jsonRoutes = jsonData.getJSONArray("routes");
    for (int i = 0; i < jsonRoutes.length(); i++) {
        JSONObject jsonRoute = jsonRoutes.getJSONObject(i);
        Route route = new Route();

        JSONObject overview_polylineJson = jsonRoute.getJSONObject("overview_polyline");
        JSONArray jsonLegs = jsonRoute.getJSONArray("legs");
        JSONObject jsonLeg = jsonLegs.getJSONObject(0);
        JSONObject jsonDistance = jsonLeg.getJSONObject("distance");
        JSONObject jsonDuration = jsonLeg.getJSONObject("duration");
        JSONObject jsonEndLocation = jsonLeg.getJSONObject("end_location");
        JSONObject jsonStartLocation = jsonLeg.getJSONObject("start_location");

        route.distance = new Distance(jsonDistance.getString("text"), jsonDistance.getInt("value"));
        route.duration = new Duration(jsonDuration.getString("text"), jsonDuration.getInt("value"));
        route.endAddress = jsonLeg.getString("end_address");
        route.startAddress = jsonLeg.getString("start_address");
        route.startLocation = new LatLng(jsonStartLocation.getDouble("lat"), jsonStartLocation.getDouble("lng"));
        route.endLocation = new LatLng(jsonEndLocation.getDouble("lat"), jsonEndLocation.getDouble("lng"));
        route.points = decodePolyLine(overview_polylineJson.getString("points"));

        routes.add(route);
    }

    listener.onDirectionFinderSuccess(routes);
}

private List<LatLng> decodePolyLine(final String poly) {
    int len = poly.length();
    int index = 0;
    List<LatLng> decoded = new ArrayList<LatLng>();
    int lat = 0;
    int lng = 0;

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

        decoded.add(new LatLng(
                lat / 100000d, lng / 100000d
        ));
    }

    return decoded;
}
}

此外,我的应用程序的目标是老人。我想用箭头显示方向。我可以使用什么方法来实现以下结果?

Showing the direction with an arrow

0 个答案:

没有答案