Skip to content

Instantly share code, notes, and snippets.

@krisrak
Created April 23, 2017 20:56
Show Gist options
  • Save krisrak/4c73ca2d51a4f0f260b47c687f49e43c to your computer and use it in GitHub Desktop.
Save krisrak/4c73ca2d51a4f0f260b47c687f49e43c to your computer and use it in GitHub Desktop.
Python script to find lat,lng within a geofence circle for csv posts exported from picodash.com
#!/usr/bin/python
import sys
import csv
from math import sin, cos, sqrt, atan2, radians
try:
filename = sys.argv[1]
geofence = sys.argv[2]
lat = geofence.split(',')[0]
lng = geofence.split(',')[1]
radius = geofence.split(',')[2]
except:
print "\nERROR: Please specify filename and geofence(lat,lng,radius)\n"
print "Usage:"
print " $ picodash_export_geofence.py data.csv 45,-122,5000\n"
print "- First param should be the csv file path"
print "- Second param should be the geofence (lat,lng,radius)\n"
sys.exit(0)
new_data=[]
# open csv file to check geofence
with open(filename, 'r') as csvfile:
csv_reader = csv.reader(csvfile)
# iterate on all rows in csv
for row_index,row in enumerate(csv_reader):
# find the lat,lng column index
if row_index == 0:
LAT_COL_NUM = None
LNG_COL_NUM = None
for col_index,col in enumerate(row):
if col == "lat":
LAT_COL_NUM = col_index
elif col == "lng":
LNG_COL_NUM = col_index
new_data.append(row)
continue
# check if lat,lng is within geofence
post_lat = row[LAT_COL_NUM]
post_lng = row[LNG_COL_NUM]
if post_lat != '' and post_lng != '':
R = 6373.0
lat1 = radians(float(post_lat))
lon1 = radians(float(post_lng))
lat2 = radians(float(lat))
lon2 = radians(float(lng))
within = float(radius)
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
distance = R * c * 1000
inside = "YES"
if distance > within:
inside = "NO"
else:
new_data.append(row)
print "Post #"+str(row_index)+ ": " +str(inside)+ " (" +str(distance) + ")"
else:
print "Post #"+str(row_index)+ ": NA"
new_filename = filename.replace('.csv','_geofence.csv')
with open(new_filename, 'w') as csvfile:
csv_writer = csv.writer(csvfile, lineterminator='\n')
csv_writer.writerows(new_data)
print "Updated CSV with location column: " + new_filename
@krisrak
Copy link
Author

krisrak commented Apr 23, 2017

This is a Python script to filter data within a geofence for posts exported from picodash.com

You have to specify the csv_filename and geofence (lat,lng,radius). The script will create a new csv with "_geofence" appended to filename.

Usage:
/usr/bin/python picodash_export_geofence.py <csv_filename> <lat,lng,radius>

Example:
/usr/bin/python picodash_export_geofence.py data.csv 45.23,-122.23,5000

@balasmeh
Copy link

where is the csv file of geofencing data?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment