Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1
Working with Your Map

SupportMapFragment.getMapAsync(...) does what it says on the tin: It gets a map object
asynchronously. If you call this from within your onCreate(Bundle), you will get a reference to a
GoogleMap once it is created and initialized.


Now that you have a GoogleMap, you can update the look of that map according to the current state of
LocatrFragment. The first thing you will want to do is zoom in on an area of interest. You will want a
margin around that area of interest. Add a dimension value for that margin.


Listing 34.10  Adding margin (res/values/dimens.xml)




16dp
16dp
100dp

Now add an updateUI() implementation to perform the zoom.


Listing 34.11  Zooming in (LocatrFragment.java)


private boolean hasLocationPermission() {
...
}


private void updateUI() {
if (mMap == null || mMapImage == null) {
return;
}


LatLng itemPoint = new LatLng(mMapItem.getLat(), mMapItem.getLon());
LatLng myPoint = new LatLng(
mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());


LatLngBounds bounds = new LatLngBounds.Builder()
.include(itemPoint)
.include(myPoint)
.build();


int margin = getResources().getDimensionPixelSize(R.dimen.map_inset_margin);
CameraUpdate update = CameraUpdateFactory.newLatLngBounds(bounds, margin);
mMap.animateCamera(update);
}


private class SearchTask extends AsyncTask<Location,Void,Void> {


Here is what you just did. To move your GoogleMap around, you built a CameraUpdate.
CameraUpdateFactory has a variety of static methods to build different kinds of CameraUpdate objects
that adjust the position, zoom level, and other properties around what your map is displaying.


Here, you created an update that points the camera at a specific LatLngBounds. You can think of a
LatLngBounds as a rectangle around a set of points. You can make one explicitly by saying what the
southwest and northeast corners of it should be.

Free download pdf