Muhammad Jamal
Muhammad Jamal

Reputation: 442

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));
}

Upvotes: 0

Views: 336

Answers (2)

Jyotman Singh
Jyotman Singh

Reputation: 11340

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

Upvotes: 1

Aldo Wachyudi
Aldo Wachyudi

Reputation: 18001

I think NPE is caused in this line

mMap.getMyLocation().getLatitude()

Also, if you want to get current location you should use different approach such as using Google Play Services or Android built-in library

Google Play Services: http://developer.android.com/training/location/retrieve-current.html

Android built-in library: http://developer.android.com/guide/topics/location/strategies.html

Upvotes: 1

Related Questions