Rounding Lat and Long to Show Approximate Location in Google Maps

11,765

Solution 1

The easiest thing to do would be either to round both coordinates to a certain number of decimal places, or add a random dither to the coordinates:

lat = Math.floor(lat*1000+0.5)/1000; (round within 0.001)

or

dither=0.001;
lat = lat + (Math.random()-0.5)*dither;

If you really want to be within a certain number of miles, you'd need to do more-complex math, probably using polar coordinates.

Solution 2

This can be done fairly simply. If you're rounding to a grid, then the latitude changes by constant amounts at all points on the planet. Longitude changes by different amounts according to how far you are from the equator.

The following code snaps latitude and longitude to an arbitrary grid size

double EARTH_RADIUS_KM = 6371;

double GRID_SIZE_KM = 1.6; // <----- Our grid size in km..

double DEGREES_LAT_GRID = Math.toDegrees(GRID_SIZE_KM / EARTH_RADIUS_KM);
//     ^^^^^^ This is constant for a given grid size.

public Location snapToGrid(Location myLoc) {
  double cos = Math.cos(Math.toRadians(myLoc.latitude));

  double degreesLonGrid = DEGREES_LAT_GRID / cos;

  return new Location (
      Math.round(myLoc.longitude / degreesLonGrid) * degreesLonGrid,
      Math.round(myLoc.latitude / DEGREES_LAT_GRID) * DEGREES_LAT_GRID);

}

Note that this will fail in the case where you are at the Pole (when the cos function approaches zero). Depending on your grid size, the results become unpredictable as you approach a latitude of +/- 90 degrees. Handling this is an exercise left for the reader :)

Share:
11,765
Callmeed
Author by

Callmeed

Husband, father, hacker, entrepreneur and photographer. Co-founder and CTO at BIG Folio and NextProof Twitter @callmeed

Updated on June 19, 2022

Comments

  • Callmeed
    Callmeed almost 2 years

    I'm displaying a Google map in my Rails app's view and will be using a marker/overlay.

    The coordinate data will be coming from a phone (GPS) and stored in my Rails app's db.

    The problem is, I don't want the precise lat/long visible in the source of my web page ... i.e. I want to mark an approximate location without giving away the true lat/long.

    How can I round/truncate the lat/long values so they are still accurate (say, within a mile)–but not too accurate?

    (Example: how would you round 35.2827524, -120.6596156 ?)