Last active
April 4, 2022 16:04
-
-
Save cartorjo/acd373e44e0cd4ed17e576606588929f to your computer and use it in GitHub Desktop.
reverse geocoding
This file contains 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
<script> | |
let data = [ | |
"Address" | |
]; | |
let myAPIKey = APIKey; | |
let url = `https://api.geoapify.com/v1/batch/geocode/search?apiKey=${myAPIKey}`; | |
fetch(url, { | |
method: 'post', | |
headers: { | |
'Accept': 'application/json', | |
'Content-Type': 'application/json' | |
}, | |
body: JSON.stringify(data) | |
}) | |
.then(getBodyAndStatus) | |
.then((result) => { | |
if (result.status !== 202) { | |
return Promise.reject(result) | |
} else { | |
console.log("Job ID: " + result.body.id); | |
console.log("Job URL: " + result.body.url) | |
return getAsyncResult(`${url}&id=${result.body.id}`, 1000, 100).then(queryResult => { | |
console.log(queryResult); | |
return queryResult; | |
}); | |
} | |
}) | |
.catch(err => console.log(err)); | |
function getBodyAndStatus(response) { | |
return response.json().then(responceBody => { | |
return { | |
status: response.status, | |
body: responceBody | |
} | |
}); | |
} | |
function getAsyncResult(url, timeout, maxAttempt) { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
repeatUntilSuccess(resolve, reject, 0) | |
}, timeout); | |
}); | |
function repeatUntilSuccess(resolve, reject, attempt) { | |
console.log("Attempt: " + attempt); | |
fetch(url) | |
.then(getBodyAndStatus) | |
.then(result => { | |
if (result.status === 200) { | |
resolve(result.body); | |
} else if (attempt >= maxAttempt) { | |
reject("Max amount of attempt achived"); | |
} else if (result.status === 202) { | |
// Check again after timeout | |
setTimeout(() => { | |
repeatUntilSuccess(resolve, reject, attempt + 1) | |
}, timeout); | |
} else { | |
// Something went wrong | |
reject(result.body) | |
} | |
}) | |
.catch(err => reject(err)); | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment