I am a beginner in Android programming. I already looked at similar questions and answers but I still can't figure out why this doesn't work. When I try this on the emulator and click a location, no marker appears. This is my code:
public class MapActivity extends AppCompatActivity implements LocationListener, OnMapReadyCallback, GoogleMap.OnMapClickListener {
private MapFragment mapFragment;
private GoogleMap googleMap;
LocationManager locationManager;
ArrayList<LocationProvider> providers;
private boolean isUpdatePosition;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
this.isUpdatePosition = true;
FragmentManager fragmentManager = getFragmentManager();
mapFragment = (MapFragment) fragmentManager.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
} // End onCreate
private void mapDisplayPosition(){
if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED ) {
this.googleMap.setMyLocationEnabled(true);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
List<String> names = locationManager.getProviders(true);
providers = new ArrayList<LocationProvider>();
for(String name : names)
providers.add(locationManager.getProvider(name));
Criteria critere = new Criteria();
// Pour indiquer la précision voulue
// On peut mettre ACCURACY_FINE pour une haute précision ou ACCURACY_COARSE pour une moins bonne précision
critere.setAccuracy(Criteria.ACCURACY_FINE);
// Est-ce que le fournisseur doit être capable de donner une altitude ?
critere.setAltitudeRequired(true);
// Est-ce que le fournisseur doit être capable de donner une direction ?
critere.setBearingRequired(true);
// Est-ce que le fournisseur peut être payant ?
critere.setCostAllowed(false);
// Pour indiquer la consommation d'énergie demandée
// Criteria.POWER_HIGH pour une haute consommation, Criteria.POWER_MEDIUM pour une consommation moyenne et Criteria.POWER_LOW pour une basse consommation
critere.setPowerRequirement(Criteria.POWER_HIGH);
// Est-ce que le fournisseur doit être capable de donner une vitesse ?
critere.setSpeedRequired(true);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 0, this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 6000, 0, this);
}
}
@Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
float zoom = 15;
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(latLng.latitude + " : " + latLng.longitude);
googleMap.clear();
if(this.isUpdatePosition){
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
this.isUpdatePosition = false;
}
googleMap.addMarker(markerOptions);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
@Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions( this, new String[] { android.Manifest.permission.ACCESS_FINE_LOCATION }, 2);
}
mapDisplayPosition();
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
mapDisplayPosition();
}
@Override
public void onMapClick(LatLng latLng) {
}
}
You need to call setOnMapClickListener
to use the OnMapClickListener
on your map:
this.googleMap.setOnMapClickListener(this);
Add it to the onMapReady
function like this:
@Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 2);
}
this.googleMap.setOnMapClickListener(this);
mapDisplayPosition();
}
Then add a marker in the onMapClick
function as follows:
@Override
public void onMapClick(LatLng latLng) {
MarkerOptions marker = new MarkerOptions()
.position(latLng);
this.googleMap.addMarker(marker);
}
Now you should be able to place markers when clicking anywhere on your map. However, notice that you are clearing your map in the onLocationChanged
function through this line:
googleMap.clear();
Which makes the new markers disappear within seconds. Assuming this is not intended behavior, fix this by commenting it out, i.e. //googleMap.clear();
.
Hope this helps! :)