Skip to content

Instantly share code, notes, and snippets.

@steinbring
Created November 3, 2021 02:29
Show Gist options
  • Save steinbring/b2ac8541b398163ef87b441d05a99492 to your computer and use it in GitHub Desktop.
Save steinbring/b2ac8541b398163ef87b441d05a99492 to your computer and use it in GitHub Desktop.
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;
}
function deg2rad(deg) {
return deg * (Math.PI/180);
}
function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
async function handleRequest(request) {
// Set the target slug
if(typeof getUrlVars(request.url)["slug"] !== 'undefined'){
slug = getUrlVars(request.url)["slug"];
}
else{
slug = '';
}
// Set the latitude
if(typeof getUrlVars(request.url)["latitude"] !== 'undefined'){
latitude = getUrlVars(request.url)["latitude"];
}
else{
latitude = request.cf.latitude;
}
// Set the longitude
if(typeof getUrlVars(request.url)["longitude"] !== 'undefined'){
longitude = getUrlVars(request.url)["longitude"];
}
else{
longitude = request.cf.longitude;
}
// API Crap
let endpoint = "https://api.wisparks.jws.app/v1/wisconsinParks.json";
const init = {
headers: {
"content-type": "application/json;charset=UTF-8",
},
}
const response = await fetch(endpoint,init);
const parksContent = await response.json();
const result = parksContent.filter(park => park.slug === slug);
// Use the lat/long values to set distance values
result[0].distance = getDistanceFromLatLonInKm(result[0].LatLongCoordinates.split(',')[0],result[0].LatLongCoordinates.split(',')[1],latitude,longitude);
return new Response(JSON.stringify(result[0], null, 2), {
headers: {
"content-type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "https://*.jws.app",
"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