'Grouping/Bucketing latitude and longitude

This is more of a logical problem than the technical one. So request you guys to please not to flag it.

I want to write a method in python, that takes two parameters -> latitude and longitude. This method should return group/bucket. The grouping should be done based on 0.05 degree.

def get_bucket(lat,lng):
  #body

Eg:

get_bucket(1.05,1.05) -> b1 get_bucket(1.05,1.03) -> b1

So its like assuming that the earth is divided in 0.05 degree grid square and any lat/long falling in this square share the same bucket.



Solution 1:[1]

There are typically 180 degrees of latitude (-90 to 90) and 360 degrees of longitude (-180 to 180).

So there are 18,000 hundredth-degree increments of latitude (i.e. -90.00, -89.99, ... 89.99, 90.00), and 36,000 hundredth-degree increments of longitude.

Let's say you put this in a two-dimensional array. If you want .05 degree increments, you'll need 3,600 (18,000/5) rows for latitude, and 7,200 columns (36,000/5) rows for latitude.

So you want to convert a longitude/latitude into two array indices. Here's one way:

  1. Take your latitude number, which will be in the range -90 to 90, and add 90 to it. That gives you a number from 0 to 180.
  2. Multiply by 100, and round up. That gives you a number from 0 to 18,000.
  3. Divide by 5.

That's your row index.

Do the same with longitude, but add 180 to get a number between 0 and 360. That provides your column number.

Example:

The location of Austin, TX is lat: 30.267, lng: -97.743

30.267 + 90 = 120.267
120.267 * 100 = 12027 (rounded up)
12027 / 5 = 2405

-97.743 + 180 = 82.257
82.257 * 100 = 8226 (rounded up)
8226 / 5 = 1645

So Austin, TX would go into bucket (2450,1645)

Of course, transforming the indexes back to latitude and longitude is just a reverse of the original transformation. For latitude, multiply by 5, divide by 100, and subtract 90.

Edit: Corrected math error.

Solution 2:[2]

Here is one implementation:

def get_bucket(lat,lng):
    int(lng/0.05)*(whatever the highest possible lat is)/0.05 + int(lat/0.05)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 devinbost
Solution 2 Maltysen