Search code examples
androidgoogle-mapsandroid-fragmentsgoogle-latitude

I am receiving null pointer exception , when i try to get mylocation from map


I am unable to get my location from map , it throws null pointer exception.

        if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        try {
            mMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapFrag)).getMap();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            mMap.setMyLocationEnabled(true);
            mMap.getUiSettings().setMyLocationButtonEnabled(true);
            mMap.getUiSettings().setZoomControlsEnabled(true);
            putMarkerOnMap(mMap.getMyLocation().getLatitude(),mMap.getMyLocation().getLongitude());
        }

It throws error at the line .. where i calling a function putMarkerOnMap(lat,lng) Here is that function

    public void putMarkerOnMap(double la , double lo){
    LatLng position = new LatLng(la,lo);
    mMap.addMarker(new MarkerOptions().position(new LatLng(la, lo)).title("Your Location"));
    CameraPosition campos = new CameraPosition.Builder().target(position).zoom(15)
            .bearing(90)
            .tilt(40)
            .build();
    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(campos));
}

Solution

  • The method getMyLocation() is deprecated. So don't use it. Instead use the FusedLocation API provided by the Google Play Services to get the current location.

    Check this