I want to create an alert / message that shows me the users geodata after the page has been loaded.
Here ist the script for the geolocation that I want to be
displayed in the alert.
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
alert("Your location is:" + getLocation());
</script>
2
Answers
Assuming the code executes without error (you haven’t specified)… This should be successfully alerting "Your location is:undefined":
Because
getLocation
doesn’t return anything. Since the information you’re looking for is asynchronous, it only exists in or after a given callback operation. That callback operation (the function where the values you want exist) is:So that’s where you’d add your alert. For example:
Using your original example below…
NOTES:
x
. Which I assume you’d defined elsewhere in your code. Otherwise what would you expect it to be and why? And surely the browser would be producing an error on the console?