-
-
Save MostAwesomeDude/1365829 to your computer and use it in GitHub Desktop.
Finding zip codes within the radius of a given address using SimpleGeo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from math import pi,sqrt,sin,cos,asin,atan2 | |
from simplegeo import Client | |
import json | |
# Instantiate the SimpleGeo Client | |
client = Client('KEY', 'SECRET') | |
context = client.context.get_context_by_address("4275 Swift Ave, San Diego, CA") | |
lat1 = float(context['query']['latitude']) | |
lon1 = float(context['query']['longitude']) | |
# Convert the initial lat, lon to radians | |
lat1 = (lat1 * pi/180) | |
lon1 = (lon1 * pi/180) | |
earths_radius = 6372.8 | |
radius = 30 | |
# Find the hypotenuse of the triangle and convert to kilometers | |
distance = sqrt( 2 * (radius**2) ) | |
distance = distance * 1.609344 | |
brng1 = (45 * pi/180) | |
brng2 = (225 * pi/180) | |
dist = distance / earths_radius | |
# Get the Southwest Lat/Lon in degrees | |
swLatRad = asin (sin(lat1) * cos(dist) + cos(lat1) * sin(dist) * cos(brng1)) | |
swLat = swLatRad * (180/pi) | |
swLonRad = lon1 + atan2(sin(brng1) * sin(dist) * cos(lat1), | |
cos(dist) - sin(lat1) * sin(swLatRad)) | |
swLon = swLonRad * (180/pi) | |
# Get the Northeast Lat/Lon in degrees | |
neLatRad = asin (sin(lat1) * cos(dist) + cos(lat1) * sin(dist) * cos(brng2)) | |
neLat = neLatRad * (180/pi) | |
neLonRad = lon1 + atan2(sin(brng2) * sin(dist) * cos(lat1), | |
cos(dist) - sin(lat1) * sin(neLatRad)) | |
neLon = neLonRad * (180/pi) | |
# Find the zip codes within the given mile radius | |
# and put them in a comma-separated string | |
bbox_ZIPs = client.context.get_context_from_bbox(swLat, swLon, neLat, neLon, features__category='Postal Code') | |
zips_list = '' | |
for zips in bbox_ZIPs['features']: | |
zips_list += zips['name'] + ',' | |
zips = zips_list[:-1] | |
print(zips) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment