MapView google maps NullPointerException?

一曲冷凌霜 提交于 2019-12-06 00:05:44

I've faced the same issue with my first attempt at GoogleMap and MapView.

The issue is that when you init the map, it takes a short while to load (which it does in the background). When you obtain the instance from the MapView, the value of the GoogleMap is still null (not initialized).

You need to use OnMapLoadedCallback here. Add an instance of this callback to the googleMap right after googleMap = mapView.getMap();. The callback body has a function called onMapLoaded(), wherein you place the following code:

googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
        .target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
        .newCameraPosition(cameraPosition));

and anything as the likes of 'googleMap.<member>'. I'm adding the edited code below for your ease.

private void setMapView() {

    try {
        MapsInitializer.initialize(getActivity().getApplicationContext());
    } catch (Exception e) {
        e.printStackTrace();
    }

    googleMap = mapView.getMap();

    googleMap.setOnMapLoadedCallback(new OnMapLoadedCallback()
    {
        @Override
        public void onMapLoaded()
        {
            // latitude and longitude
                double latitude = 17.385044;
                double longitude = 78.486671;

                // create marker
                MarkerOptions marker = new MarkerOptions().position(
                    new LatLng(latitude, longitude)).title("Hello Maps");

                // Changing marker icon
                marker.icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

                // adding marker
                googleMap.addMarker(marker);
                CameraPosition cameraPosition = new CameraPosition.Builder()
                        .target(new LatLng(17.385044, 78.486671)).zoom(12).build();
                googleMap.animateCamera(CameraUpdateFactory
                        .newCameraPosition(cameraPosition));

            // Perform any camera updates here

        }
    });
  } 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!