Obtain Driving Directions with Google Maps API v2
Getting driving directions between two locations is a common requirement for many mapping applications. However, the code you've provided only draws a straight line between the points, rather than providing turn-by-turn directions.
Solution Using Android GoogleDirection Library
To retrieve driving directions, you can utilize the Android GoogleDirectionLibrary, a recently released library by akexorcist. Here's a modified code snippet using the library:
import com.akexorcist.googledirection.DirectionCallback; import com.akexorcist.googledirection.GoogleDirection; import com.akexorcist.googledirection.model.Direction; import com.akexorcist.googledirection.model.Leg; import com.akexorcist.googledirection.model.Route; import com.akexorcist.googledirection.util.DirectionConverter; ... // Replace with your API key String apiKey = "YOUR_API_KEY"; GoogleDirection.withServerKey(apiKey) .from(new LatLng(12.917745600000000000,77.623788300000000000)) .to(new LatLng(12.842056800000000000,7.663096499999940000)) .execute(new DirectionCallback() { @Override public void onDirectionSuccess(Direction direction, String rawBody) { if (direction.isOK()) { Route route = direction.getRouteList().get(0); Leg leg = route.getLegList().get(0); // Draw the path (Polylines) List<LatLng> directionPositionList = DirectionConverter.decodePoly(leg.getPolylinePoint()); Polyline line = mMap.addPolyline(new PolylineOptions() .addAll(directionPositionList) .width(5) .color(Color.RED)); // Display turn-by-turn instructions String[] instructions = DirectionConverter.provideInstructionList(leg); for (String instruction : instructions) { Log.d("Direction", instruction); } } else { // Handle error } } @Override public void onDirectionFailure(Throwable t) { // Handle error } });
With this modified code, you should be able to obtain driving directions between the two locations, including turn-by-turn instructions.
The above is the detailed content of How to Get Turn-by-Turn Driving Directions Using Google Maps API v2?. For more information, please follow other related articles on the PHP Chinese website!