Skip to content

Instantly share code, notes, and snippets.

@thomaswilburn
Last active January 6, 2026 15:43
Show Gist options
  • Select an option

  • Save thomaswilburn/267c64eb210a5fa8d3255b64ec2b4210 to your computer and use it in GitHub Desktop.

Select an option

Save thomaswilburn/267c64eb210a5fa8d3255b64ec2b4210 to your computer and use it in GitHub Desktop.
Make sandboxed JSONP calls to the Census geocoder
function jsonp(url, callback = "callback") {
return new Promise((ok, fail) => {
let iframe = document.createElement("iframe");
let onmessage = function(e) {
if (e.source == iframe.contentWindow) {
iframe.remove();
window.removeEventListener("message", onmessage);
ok(e.data.response);
}
};
window.addEventListener("message", onmessage);
iframe.style.width = "1px";
iframe.style.height = "1px";
iframe.style.position = "absolute";
iframe.style.left = "-1000px";
iframe.sandbox = "allow-scripts";
let doc = `
<script>
window.${callback} = function(response) {
let message = { response };
window.parent.postMessage(message, "${window.location.origin}");
};
let script = document.createElement("script");
let params = new URLSearchParams(window.location.search);
script.src = "${url}";
document.documentElement.append(script);
</script>
`;
iframe.srcdoc = doc;
document.body.append(iframe);
});
}
export async function geocode(address) {
let searchType = "address";
let params = {
format: "jsonp",
callback: "callback",
benchmark: "Public_AR_Current"
};
if (typeof address == "string") {
searchType = "onelineaddress";
params.address = address;
} else {
Object.assign(params, address);
}
let url = new URL(`https://geocoding.geo.census.gov/geocoder/locations/${searchType}`);
for (var k in params) {
url.searchParams.set(k, params[k]);
}
let response = await jsonp(url.toString());
return response?.result?.addressMatches[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment