I am using Google Maps V2 for my application, I need to fit and center a Polyline on my map. At first, I change the bottom padding of my map using mGoogleMap.setPadding(0,0,0,bottomPadding)
. after that I will plot the polyline on the map. lastly, I will focus all of the polylines using latlngbounds where all of the polyline points are included and the animate the camera of the map. But unfortunately the polylines are not properly displayed because most of the time the polylines are out the camera.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setMapPadding(0,0,0,100);
getDirections ("","","","",""); // http query to google directions api,
//assume that the parameters here are valid
}
private void getDirections (String key, String origin, String destination, String unit){
mService.getDirections(key, origin, destination, unit, new Callback<Directions>() {
@Override
public void success(final Directions directions, Response response) {
if (directions.getStatus().equals("OK")) {
String distance = directions.getRoutes().get(0).getLegs().get(0)
.getDistance().getText();
LatLngBounds latLngBounds = createDirectionBounds(directions.getRoutes()
.get(0).getOverviewPolyline());
mMapFragment.plotTravelDirections(directions.getRoutes().get(0)
.getOverviewPolyline().getPoints());
mMapFragment.showTravelDirections(latLngBounds);
}
}
@Override
public void failure(RetrofitError error) {}
});
}
private LatLngBounds createDirectionBounds(OverviewPolyline overviewPolyline){
LatLngBounds.Builder builder = new LatLngBounds.Builder();
List<LatLng> decodedPolyline = PolyUtil.decode(overviewPolyline.getPoints());
for(int ctr=0; ctr <decodedPolyline.size()-1; ctr++){
builder.include(decodedPolyline.get(ctr));
}
return builder.build();
}
Setting the map padding method :
public void setMapPadding (int left, int top, int right, int bottom){
mGoogleMap.setPadding(left, top, right, bottom);
}
Plotting the polylines:
public void plotTravelDirections (String overviewPolyLine){
mGoogleMap.clear();
List<LatLng> decodedPolyLine = PolyUtil.decode(overviewPolyLine);
mGoogleMap.addPolyline(new PolylineOptions().addAll(decodedPolyLine)
.color(ContextCompat.getColor(getActivity(), R.color.hitch_red)).geodesic(true));
BitmapDescriptor pickUpMarker = BitmapDescriptorFactory.fromResource(R.drawable.ic_marker);
BitmapDescriptor destinationMarker = BitmapDescriptorFactory.fromResource(R.drawable.ic_end_marker);
mGoogleMap.addMarker(new MarkerOptions().position(decodedPolyLine.get(0)).icon(pickUpMarker));
mGoogleMap.addMarker(new MarkerOptions().position(decodedPolyLine
.get(decodedPolyLine.size() - 1)).icon(destinationMarker));
}
Fitting the polyline on the camera:
public void showTravelDirections (LatLngBounds latLngBounds){
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(latLngBounds, 0);
mGoogleMap.animateCamera(cameraUpdate);
}