I want to get the geolocation of a user and then calculate the distance d to another location and submit it via the form to my flask backend. However the script is "to fast" to allow the user to confirm that the location is going to be tracked. I only want to use one button, how can I postpone the script to wait for the user input?
<form name="koordinaten" action="#" method="post" >
<!--form um die koordinaten ans backend weiterzugeben-->
<input type="text" name="comment" minlength="4" maxlength="140" >
<input type="hidden" name="location" id="distance" />
<input type="submit" value="submit" onclick="getLocation()">
</form>
<script>
var distanz = document.getElementById("breite");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(distance, showError);
} else {
distance.innerHTML = "Geolocation is not supported by this browser.";
}
}
function distance(position) {
var breite = position.coords.latitude * Math.PI/180;
var laenge = position.coords.longitude* Math.PI/180;
let breite2= 52.4929583248418*Math.PI/180;
let laenge2=13.49116907310046*Math.PI/180;
let d = 6731000*Math.acos(Math.sin(breite2)*Math.sin(breite)+Math.cos(breite2)*Math.cos(breite)*Math.cos(laenge-laenge2));
document.getElementById("distance").value = d;
}
addEventListener
instead of intrinsic event attributessubmit
method of the form once the data is availableKey changes highlighted with ❇️
<!-- ❇️ --><form id="koordinaten" action="#" method="post">
<!--form um die koordinaten ans backend weiterzugeben-->
<input type="text" name="comment" minlength="4" maxlength="140" />
<input type="hidden" name="location" id="distance" />
<!-- ❇️ --><input type="submit" value="submit" />
</form>
<script>
const form = document.getElementById("koordinaten");
form.addEventListener("submit", getLocation);
var distanz = document.getElementById("breite");
/* ❇️ */function getLocation(event) {
/* ❇️ */ event.preventDefault();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(distance, showError);
} else {
distance.innerHTML = "Geolocation is not supported by this browser.";
}
}
function distance(position) {
var breite = (position.coords.latitude * Math.PI) / 180;
var laenge = (position.coords.longitude * Math.PI) / 180;
let breite2 = (52.4929583248418 * Math.PI) / 180;
let laenge2 = (13.49116907310046 * Math.PI) / 180;
let d =
6731000 *
Math.acos(
Math.sin(breite2) * Math.sin(breite) +
Math.cos(breite2) * Math.cos(breite) * Math.cos(laenge - laenge2)
);
document.getElementById("distance").value = d;
/* ❇️ */ form.submit();
}
</script>