Created
October 16, 2021 15:01
-
-
Save steinbring/ee58c825ab64e618e039c82245aa84b1 to your computer and use it in GitHub Desktop.
This is the code behind the https://geolocation-json.joe.workers.dev/ cloudflare worker
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
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) { | |
// Is it a get request? | |
if(request.method == 'GET'){ | |
// 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; | |
} | |
}else{ | |
latitude = request.cf.latitude; | |
longitude = request.cf.longitude; | |
} | |
// API Crap | |
let endpoint = "https://www.mapquestapi.com/geocoding/v1/reverse?key={ MAPQUEST API KEY GOES HERE }&location="+latitude+"%2C"+longitude+"&outFormat=json&thumbMaps=false"; | |
const init = { | |
headers: { | |
"content-type": "application/json;charset=UTF-8", | |
}, | |
} | |
const response = await fetch(endpoint,init) | |
const mqContent = await response.json() | |
// The struct that holds the details of who the user is | |
let user = { | |
latitude:latitude, | |
longitude:longitude, | |
cfCountry:request.cf.country, | |
cfCity:request.cf.city, | |
cfLatitude:request.cf.latitude, | |
cfLongitude:request.cf.longitude, | |
cfPostalcode:request.cf.postalCode, | |
cfRegion:request.cf.region, | |
cfRegioncode:request.cf.regionCode, | |
cfTimezone:request.cf.timezone, | |
mqStreet:mqContent.results[0].locations[0].street, | |
mqCity:mqContent.results[0].locations[0].adminArea5, | |
mqState:mqContent.results[0].locations[0].adminArea3, | |
mqZip:mqContent.results[0].locations[0].postalCode | |
} | |
return new Response(JSON.stringify(user, null, 2), { | |
headers: { | |
"content-type": "application/json;charset=UTF-8" | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment