Skip to content

Instantly share code, notes, and snippets.

@steinbring
Created November 22, 2021 02:57
Show Gist options
  • Save steinbring/c58f4fa48626d3554bbd972018cb4ad2 to your computer and use it in GitHub Desktop.
Save steinbring/c58f4fa48626d3554bbd972018cb4ad2 to your computer and use it in GitHub Desktop.
The code behind https://addresstocoordinates.joe.workers.dev/?q=87714 (An API for converting from a municipality or zip code to latitude/longitude coordinates)
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
function getUrlVars(url) {
var vars = {};
var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
async function handleRequest(request) {
// What are they searching for?
if(typeof getUrlVars(request.url)["q"] !== 'undefined'){
query = getUrlVars(request.url)["q"];
}
else{
// If they aren't passing anything in, don't give them anything back
return new Response(JSON.stringify(null, null, 2), {
headers: {
"content-type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET",
"Access-Control-Max-Age": "86400",
}
})
}
let endpoint = null;
// Are they looking for a ZIP Code?
if(!isNaN(parseFloat(query))){
// API Crap
endpoint = "https://gist.githubusercontent.com/steinbring/17b4652c6b9283b28eb3e2c2320f8cc2/raw/796f8eacdf6eb33010683e328fb51e734262ed6a/zipCodeToLatLong.json";
}else{
// Are they looking for a city/village/town?
// API Crap
endpoint = "https://gist.githubusercontent.com/steinbring/b9dc9d2a47acfe4fcf2613d6d0b1154b/raw/af0d309ed7f11a58db3e043fd013f9318893a1f7/cityStateToLatLong.json";
}
// API Crap
const init = {
headers: {
"content-type": "application/json;charset=UTF-8",
},
}
const response = await fetch(endpoint,init);
const result = await response.json();
// Do a keyword search of either the zip codes or the municipalities, depending on what they are looking for
let locations = null;
// Are they looking for a ZIP Code?
if(!isNaN(parseFloat(query))){
// API Crap
locations = result.filter(location => location.zip.toString().startsWith(query));
}else{
// Are they looking for a city/village/town?
// API Crap
locations = result.filter(location => location.city.startsWith(query));
}
return new Response(JSON.stringify(locations, null, 2), {
headers: {
"content-type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET",
"Access-Control-Max-Age": "86400",
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment