Search code examples
androidgoogle-mapsnullpointerexceptionlocationmanager

Trying to set marker on my current location on google maps gives Nullpointer exception


I have integrated Google Maps in my Android project. I am getting the view of the map on my device. I want to set the marker to my current location. I have done the following coding but it gives me a Null Pointer Exception on line 43 which is the following line

mMap.addMarker(new MarkerOptions() .position(new LatLng(location.getLatitude(), location.getLongitude())) .title("Hello world"));

My codes are as below. Please guide me step by step as to what is going wrong.

     public class location extends Activity implements LocationListener {
private GoogleMap mMap;
LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map_location);

    mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.the_map)).getMap();
    mMap.setMyLocationEnabled(true);

    //mMap.addMarker(new MarkerOptions());

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); 
    Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

    mMap.addMarker(new MarkerOptions()
    .position(new LatLng(location.getLatitude(), location.getLongitude()))
    .title("Hello world"));


}
@Override
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
    mMap.animateCamera(cameraUpdate);

   // locationManager.removeUpdates(this);


}

Solution

  • Try below Code it worked for me..

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map_location);
        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
    
        // Showing status
        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
    
            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();
    
        }else { // Google Play Services are available
    
            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    
            // Getting GoogleMap object from the fragment
            googleMap = fm.getMap();
    
            // Enabling MyLocation Layer of Google Map
            googleMap.setMyLocationEnabled(true);
    
            // Getting LocationManager object from System Service LOCATION_SERVICE
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    
            // Creating a criteria object to retrieve provider
            Criteria criteria = new Criteria();
    
            // Getting the name of the best provider
            String provider = locationManager.getBestProvider(criteria, true);
    
            // Getting Current Location
            Location location = locationManager.getLastKnownLocation(provider);
    
            LocationListener locationListener = new LocationListener() {
              void onLocationChanged(Location location) {
              // redraw the marker when get location update.
              drawMarker(location);
            }
    
            if(location!=null){
               //PLACE THE INITIAL MARKER              
               drawMarker(location);
            }
            locationManager.requestLocationUpdates(provider, 20000, 0, locationListener);
        }
    }
    
    private void drawMarker(Location location){
        googleMap.clear();
        LatLng currentPosition = new LatLng(location.getLatitude(),location.getLongitude());
        googleMap.addMarker(new MarkerOptions()
        .position(currentPosition)
        .snippet("Lat:" + location.getLatitude() + "Lng:"+ location.getLongitude()));
        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
        .title("ME"));
    }