0

In my App users use a map to mark their location. When new users want to create their location I would like to prevent them from putting their marker to close to already existing markers, if possible to specify mandatory distance between markers for example 10 or 20 meters.

Thank you.

Arlind Hajredinaj
  • 8,380
  • 3
  • 30
  • 45
Munez NS
  • 1,011
  • 1
  • 12
  • 31
  • Can you post the code that you have tried – Arlind Hajredinaj Jul 29 '15 at 15:07
  • 1
    One solution would be to check the distance after the marker is dropped using the Haversine formula and show an error if too close. See Haversine formula implementation here: http://stackoverflow.com/a/27943/1007510 – Chris Feist Jul 29 '15 at 15:21

1 Answers1

1

This is actually very simple, all you need to do is check if the point that the user clicks on is further than your required distance before removing the previous Marker and adding the new one.

You can use the Location.distanceBetween() method to do the distance check.

First, create your Marker reference as an instance variable of the Activity:

Marker marker;

Then, in your OnMapClickListener, add the logic to only move the Marker that the user chooses as the current location if the distance is greater than your defined minimum distance, 20 meters in this example:

   mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

        @Override
        public void onMapClick(LatLng point) {

            if (marker != null) {
                LatLng markerPoint = marker.getPosition();

                float[] distance = new float[2];

                Location.distanceBetween(point.latitude, point.longitude,
                        markerPoint.latitude, markerPoint.longitude, distance);

                //check if new position is at least 20 meters away from previous selection
                if( distance[0] > 20 ){
                    //remove previous Marker
                    marker.remove();

                    //place marker where user just clicked
                    marker = mMap.addMarker(new MarkerOptions().position(point).title("My Location")
                            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));

                }
                else{
                    //Alert the user to select a location further away from the one already selected
                    Toast.makeText(MainActivity.this, "Please select a different location.", Toast.LENGTH_SHORT).show();
                }
            }
            else {

                //No previous selection, place marker where user just clicked
                marker = mMap.addMarker(new MarkerOptions().position(point).title("My Location")
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
            }
        }
    });
Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137