Created
September 8, 2015 23:22
-
-
Save veesa/69668773779cdf40ab62 to your computer and use it in GitHub Desktop.
A Script to Calculate the nearest establishments to a given postcode and distance
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
import math | |
EARTH_DIAMETER = 2 * 6378.2 | |
PI = 3.14159265 | |
RAD_CONVERT = PI / 180.0 | |
postcodes = open('geoserve_postcodes.csv', 'r') | |
given_postcode = 'CB24 6AJ' | |
given_distance = 3000.0 # The distance is given in metres | |
my_location = None | |
data = None | |
class Postcode: | |
def __init__(self, line): | |
data = line.split(',') | |
self.postcode = data[0] | |
self.east = data[1] | |
self.north = data[2] | |
self.latitude = data[3] | |
self.longitude = data[4].strip('\n') | |
def calc_distance(self, loc): | |
lat1 = self.latitude | |
lon1 = self.longitude | |
lat2 = loc.latitude | |
lon2 = loc.longitude | |
# convert degrees to radians | |
lat1 = (float(lat1) * RAD_CONVERT) | |
lat2 = (float(lat2) * RAD_CONVERT) | |
# find the deltas | |
delta_lat = lat2 - lat1 | |
delta_lon = (float(lon2) - float(lon1)) * RAD_CONVERT | |
# Find the great circle distance in km | |
temp = pow(math.sin(delta_lat/2),2) + math.cos(lat1) * math.cos(lat2) * pow(math.sin(delta_lon/2),2) | |
return EARTH_DIAMETER * math.atan2(math.sqrt(temp),math.sqrt(1-temp)) | |
# Create a Postcode object from the given_postcode | |
for location in postcodes: | |
info = location.split(',') | |
if given_postcode == info[0]: | |
my_location = Postcode(location) | |
postcodes.close() | |
break | |
# Get the name of the pub/s for a given postcode | |
def get_pub(postcode): | |
return_list = [] | |
with open('geoserve_pubs.csv', 'r') as p: | |
for lines in p: | |
if postcode in lines: | |
info = lines.split(',') | |
return_list.append(info[0].strip('\n')) | |
return return_list | |
if postcodes.closed: | |
with open('geoserve_postcodes.csv', 'r') as postcodes: | |
for line in postcodes: | |
data = Postcode(line) | |
distance_km = my_location.calc_distance(data) | |
distance_m = distance_km*1000 | |
if round(distance_m) < given_distance: | |
pub_name = get_pub(data.postcode) | |
if pub_name: | |
print str(pub_name) + ' - ' + str(distance_m) | |
postcodes.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment