MapView embedding a GoogleMap in an existing layout
suggest changeIt is possible to treat a GoogleMap as an Android view if we make use of the provided MapView class. Its usage is very similar to MapFragment.
In your layout use MapView as follows:
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Optional map: attributes, which are not set in the sample above:
map:mapTypesets the initial map typemap:zOrderOnTopcontrols whether the map view's surface is placed on top of its windowmap:useViewLifecycle, on aMapFragment, ties the map lifecycle to the fragment's view or to the fragment itselfmap:uiCompassenables or disables the compassmap:uiRotateGesturesenables or disables rotate gesturesmap:uiScrollGesturesenables or disables scroll gesturesmap:uiTiltGesturesenables or disables tilt gesturesmap:uiZoomGesturesenables or disables zoom gesturesmap:uiZoomControlsenables or disables the zoom controlsmap:liteModecreates the map in lite modemap:uiMapToolbarenables or disables the map toolbarmap:ambientEnabledenables ambient-mode stylingmap:cameraMinZoomPreferencesets a preferred lower bound for camera zoommap:cameraMaxZoomPreferencesets a preferred upper bound for camera zoom
Your activity needs to implement the OnMapReadyCallback interface in order to work:
/**
* This shows how to create a simple activity with a raw MapView and add a marker to it. This
* requires forwarding all the important lifecycle methods onto MapView.
*/
public class RawMapViewDemoActivity extends AppCompatActivity implements OnMapReadyCallback {
private MapView mMapView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.raw_mapview_demo);
mMapView = (MapView) findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this);
}
@Override
protected void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
public void onMapReady(GoogleMap map) {
map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
@Override
protected void onPause() {
mMapView.onPause();
super.onPause();
}
@Override
protected void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
}
}
Play services MapView also expects onStart and onStop to be forwarded. This sample does not.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents