Look if current location is near marker

896 views Asked by At

I have a Google Maps API Activity and want the markes only to be clickable if the user is in a certain radius to them. How is the best way to do this? This is how I set my markers:

Marker marker1 = googleMap.addMarker(new MarkerOptions()
            .position(new LatLng(49.793012, 9.926201))
            .title(getString(R.string.Title1))
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
    Marker marker2 = googleMap.addMarker(new MarkerOptions()
            .position(new LatLng(49.792742, 9.939118))
            .title(getString(R.string.Title2))
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
    Marker marker3 = googleMap.addMarker(new MarkerOptions()
            .position(new LatLng(49.793349, 9.932558))
            .title(getString(R.string.Title3))
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));

Solution code:

LatLng markerPosition = marker.getPosition();
myLocation = locationManager.getLastKnownLocation(provider);
Location markerLoc = new Location("marker");
markerLoc.setLatitude(markerPosition.latitude);
markerLoc.setLongitude(markerPosition.longitude);
float meters = myLocation.distanceTo(markerLoc);
1

There are 1 answers

0
Skizo-ozᴉʞS ツ On

You can get the LatLng of the markers by marker.getPosition(); then you can compare it with the CurrentLocation. To do this, you can check this post, and next you can make clickable or notclickable a marker as follows:

getMap().setOnMarkerClickListener(new OnMarkerClickListener() {
    public boolean onMarkerClick(Marker marker) {
        onMapClick(marker.getPosition());
        return true;
    }
});

If you return true for the function, it means that you've accepted the occurred click event on your marker; otherwise, you've not accepted it.

Moreover, you can do it with:

MarkerOptions.clickable and Marker.setClickable.

This is just a guide who how I would do what you want. hope it helps. :)