I have looked at examples on how to get a location when a page loads. I found this particularly question helpful: (get location when pages loads).
However, for testing purposes, I was hoping to build from this example and not display the coordinates, but rather craft a get request that includes the coordinates.
How would I accomplish this?
Best regards, Fredrik
You can accomplish this by waiting for the callback of the position to send the location to your API with XMLHttpRequest
.
Here's an example:
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(sendLocation);
} else {
alert("Geolocation is not supported by this browser.");
}
function sendLocation(position){
var latlng = {lat: position.coords.latitude, lng: position.coords.longitude};
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert('Success');
}
};
xhttp.open("POST", "uploadurl", true);
xhttp.send(JSON.stringify(latlng));
}