Search code examples
javaandroidgoogle-mapsgeolocationmaps

Google Maps null object reference on move camera method


I am trying to work on google maps i.e. getting current location with marker, searching location and adding a marker according to that searched location. I am getting this error

Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.moveCamera(com.google.android.gms.maps.CameraUpdate)' on a null object reference

I do not understand why I am getting this, i think there may be a problem with my instantiating my GoogleMap variable, but I don't know how to work around that. Here is my code:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
Location mLocation;
Location sLocation;
FusedLocationProviderClient client;
private static final int Request_Code = 101;
EditText txtSrch;
ImageButton btnSrch;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    client = LocationServices.getFusedLocationProviderClient(this);
    getLastLocation();

btnSrch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            geolocate();
        }
    });
}

I made these methods:

private void geolocate(){
       String search = txtSrch.getText().toString().trim();
       Geocoder geocoder = new Geocoder(MapsActivity.this);
       List<Address> list = new ArrayList<>();

   try{
        list = geocoder.getFromLocationName(search, 1);


   }
   catch (IOException e){
        e.printStackTrace();
   }

   if(list.size() > 0){
       Address address = list.get(0);
       moveCamera(new LatLng(address.getLatitude(), address.getLongitude()), 6, "Searched Location");
   }



}




private void moveCamera(LatLng latLng, float zoom, String title){
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
        MarkerOptions options = new MarkerOptions()
                .position(latLng)
                .title(title);
        mMap.addMarker(options);
   }

private void getLastLocation() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]
                {android.Manifest.permission.ACCESS_FINE_LOCATION}, Request_Code);
        return;
    }
    Task<Location> task = client.getLastLocation();
    task.addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            if(location != null){
                mLocation = location;
                Toast.makeText(getApplicationContext(),mLocation.getLatitude()+""+mLocation.getLongitude(), Toast.LENGTH_SHORT).show();
                double myLong = mLocation.getLongitude();
                double myLat = mLocation.getLatitude();
                SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
                supportMapFragment.getMapAsync(MapsActivity.this);
            }
        }
    });
}

@Override
public void onMapReady(GoogleMap googleMap) {
   LatLng latLng = new LatLng(mLocation.getLatitude(), mLocation.getLongitude());
   MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("You Are Here");
   googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
   googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 6));
   googleMap.addMarker(markerOptions);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode){
        case Request_Code:
            if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                getLastLocation();
            }
            break;
    }
}
}

I honestly think there is a problem with instantiating the mMap variable, I just don't know what to do about it. Any help would be appreciated


Solution

  • Yes.You are correct.Need to initiate your mMap.

    @Override
    public void onMapReady(GoogleMap googleMap) {
    mMap=googleMap;
    }
    
    //And before move camera, check mMap is not null
    
    private void moveCamera(LatLng latLng, float zoom, String title){
    if(mMap!=null){
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
            MarkerOptions options = new MarkerOptions()
                    .position(latLng)
                    .title(title);
            mMap.addMarker(options);
       }}