Rounding Lat and Long to Show Approximate Location in Google Maps

旧时模样 提交于 2019-12-04 12:18:57

问题


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 ?)


回答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.




回答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 :)




回答3:


Check out my solution which doesn't involve random numbers, and will provide consistent results between queries:

Is there any easy way to make GPS coordinates coarse?




回答4:


Try rounding to two decimal places.



来源:https://stackoverflow.com/questions/5269703/rounding-lat-and-long-to-show-approximate-location-in-google-maps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!