In the <body>, place the function (getLocation) that will run when page loads.
The <script> contains what the function will do. The (showPosition) function is what will happen to the location data.
There is a file in the "xhttp.open" line that will need to be created separately (noticeGeoDB.php).
<body>
<div><p id="loc1"></p></div> <!-- THIS IS WHERE LOCATION WILL BE SHOWN ON WEB SITE-->
<script>
const x = document.getElementById("loc1"); //THIS NEEDED TO SHOW LOCATION ON WEB SITE
function getLocation(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition, showError);
}else{
x.innerHTML = "Location not supported";
}
}
function showPosition(position){
const xhttp = new XMLHttpRequest();
x.innerHTML = position.coords.latitude + "," + position.coords.longitude; //THIS WILL SHOW LOCATION ON WEB SITE
xhttp.open("POST", "noticeGeoDB.php?lat=" + position.coords.latitude + "&long=" + position.coords.longitude); //SEND TO FILE
xhttp.send();
console.log("Lat:" + position.coords.latitude + "," + "Long:" + position.coords.longitude)
}
function showError(error) {
console.warn("Geolocation error:", error.message);
}
getLocation(); //RUNS SCRIPT
</script>
This file needs to be created. The first line creates a "noticeGeo.txt" file and appends the "noticetxt" data to it.
<?php
$noticefile = fopen("noticeGeo.txt", "a");
$noticetxt = date("m-d-Y") . date(" h:i:sa") . " IP: " . $_SERVER['REMOTE_ADDR'] . " lat: " . $_GET["lat"] . " , long: " . $_GET["long"] . "\n";
fwrite($noticefile, $noticetxt);
fclose($noticefile);
?>