Skip to content

Instantly share code, notes, and snippets.

@joshsmith
Created November 18, 2011 22:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joshsmith/1378009 to your computer and use it in GitHub Desktop.
Save joshsmith/1378009 to your computer and use it in GitHub Desktop.
Finding zip codes within the radius of a given address using SimpleGeo (with JS!)
$(document).ready(function() {
simplegeo_key = 'TOKEN';
var places_client = new simplegeo.Places12Client(simplegeo_key);
var context_client = new simplegeo.ContextClient(simplegeo_key);
var zips = {
zips: ''
};
// Given an address and radius (and the SimpleGeo client), returns
// a comma-separated list of zip codes within that radius.
function get_nearby_zips(address, radius, places_client) {
var location = {
lon: 0,
lat: 0
};
var something = context_client.getContextFromAddress(address, function(err, data) {
if(err) {
// Handle the error
return false;
} else {
location.lat = parseFloat(data.query.latitude);
location.lon = parseFloat(data.query.longitude);
var pi = Math.PI;
var rads = pi / 180;
var degs = 180 / pi;
var lat = location.lat * rads;
var lon = location.lon * rads;
var earths_radius = 6372.8;
var distance = Math.sqrt(2 * Math.pow(radius,2)); // Find the hypotenuse
distance = distance * 1.609344; // Convert to kilometers
var ne_bearing = 45 * rads;
var sw_bearing = 225 * rads;
var sw_lat_rad = Math.asin(Math.sin(lat) * Math.cos(distance/earths_radius) +
Math.cos(lat) * Math.sin(distance/earths_radius) * Math.cos(ne_bearing));
var sw_lat = sw_lat_rad * degs;
var sw_lon_rad = lon + Math.atan2(Math.sin(ne_bearing) * Math.sin(distance/earths_radius) *
Math.cos(lat), Math.cos(distance/earths_radius) - Math.sin(lat) * Math.sin(sw_lat_rad));
var sw_lon = sw_lon_rad * degs;
var ne_lat_rad = Math.asin(Math.sin(lat) * Math.cos(distance/earths_radius) +
Math.cos(lat) * Math.sin(distance/earths_radius) * Math.cos(sw_bearing));
var ne_lat = ne_lat_rad * degs;
var ne_lon_rad = lon + Math.atan2(Math.sin(sw_bearing) * Math.sin(distance/earths_radius) *
Math.cos(lat), Math.cos(distance/earths_radius) - Math.sin(lat) * Math.sin(ne_lat_rad));
var ne_lon = ne_lon_rad * degs;
url = 'https://api.simplegeo.com/1.0/context/' + sw_lat + ',' + sw_lon + ',' + ne_lat + ',' + ne_lon;
url += '.json?features__category=Postal+Code&token=' + simplegeo_key;
$.getJSON(url, function(data) {
var bbox_zips = [];
$.each(data.features, function(k, v) {
bbox_zips[k] = v.name;
});
zips.zips = bbox_zips.join(",");
});
}
});
}
get_nearby_zips("444 W Main St, Lock Haven, PA", 10, places_client);
console.log(zips); // returns comma-separated string of zips
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment