I am trying to implement OnMapLongClickListener
to my map application so that whenever a user long-clicks on the screen, a marker appears in the corresponding location.
My MainActivity class is as follows:
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener {
private GoogleMap mMap;
@Override
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.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mMap.setOnMapLongClickListener(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Hatfield and move the camera
LatLng hatfield = new LatLng(51.7471060, -0.22978);
mMap.addMarker(new MarkerOptions()
.position(hatfield)
.title("Hertfordshire Times")
.snippet("Hertfordshire Lecturer wins Nobel Prize")
.draggable(true));
mMap.moveCamera(CameraUpdateFactory.newLatLng(hatfield));
mMap.addCircle(new CircleOptions()
.center(hatfield)
.fillColor(0x5500ff00)
.strokeColor(Color.WHITE).radius(60));
}
@Override
public void onMapLongClick(final LatLng latLng) {
if(mMap != null) {
Toast.makeText(this, "Long press", Toast.LENGTH_LONG).show();
mMap.addMarker(new MarkerOptions()
.position(latLng)
.title("You placed a marker here")
.icon(BitmapDescriptorFactory.defaultMarker()));
}
}
}
Once the OnMapLongClick
method runs, it throws a NullPointerException
(a snippet of the error is shown below):
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setOnMapLongClickListener(com.google.android.gms.maps.GoogleMap$OnMapLongClickListener)' on a null object reference
at com.example.paulmbw.map_application_fyp.MapsActivity.onCreate(MapsActivity.java:29)
Any idea what I'm doing wrong? I have seen similar answers on Stack but cannot seem to find a solution for my problem. Any help will be greatly appreciated.
Thanks.