1

I have a collection of items and some of them may have the same coordinates.
As a result they are displayed as 1 marker in Google Maps since the markers are painted one on top of each other.
To address this I tried to "move" those markers by a few meters so that the markers do not collide.
I would like to move them to a 5 meters from where their location is.
I did the following following another SO answer:

double newLat = item.getLatitude() + (Math.random() - .005) / 15000;    
double newLon = item.getLongitude() + (Math.random() - .005) / 15000;    

The problem is that this moves the items a bit but it seems that some are moved by 4m others by 3m and I would like if possible to ensure that I will be between 4-6 meters (min/max)
How can I change my formula to do this?

Community
  • 1
  • 1
Jim
  • 18,826
  • 34
  • 135
  • 254

1 Answers1

5

I think that the best option could be using the SphericalUtil. computeOffset method from the Google Maps Android API Utility Library:

computeOffset

public static LatLng computeOffset(LatLng from,
                               double distance,
                               double heading)

Returns the LatLng resulting from moving a distance from an origin in the specified heading (expressed in degrees clockwise from north).

Parameters:

from - The LatLng from which to start.

distance - The distance to travel.

heading - The heading in degrees clockwise from north.

In your case you can set the distance to be 5 meters and randomise the heading parameter to be something between 0 and 360 degrees:

Random r = new Random();
int randomHeading = r.nextInt(360);
LatLng newLatLng = SphericalUtil.computeOffset(oldLatLng, 5, randomHeading);
antonio
  • 18,044
  • 4
  • 45
  • 61
  • The javadoc does not say that the distance is in meters does it? – Jim Mar 22 '17 at 09:54
  • No, it doesn't, but you can compute the distance between `oldLatLng` and `newLatLng` using `SphericalUtil.computeDistanceBetween(oldLatLng, newLatLng)` (which according to the documentation returns the distance in meters) and you will see that the distance is 5 meters – antonio Mar 22 '17 at 11:25
  • I did and it is so but how did you assume that it is in meters? Is it standard in the Google Maps API to use meters? – Jim Mar 22 '17 at 18:35
  • As far as I know all the classes and methods from the Google Maps Android API Utility Library uses meters as the unit. Anyway your can take a look at the [source code](https://github.com/googlemaps/android-maps-utils/blob/master/library/src/com/google/maps/android/SphericalUtil.java) – antonio Mar 22 '17 at 18:40