I need to get the latitude and longitude coordinates of a user in a webrowser to calculate the distance between the user and various restaurants. to do this, first I need the latitude and longitude,
I've been using this code to get lat and long, but i cant seem to get the actaul values saved to do calculations, and it seems quite a few people have had this issue too, and after doing a lot of searching, I still have not found a solution.
<script type="text/javascript">
var jArray= <?php echo json_encode($restaurant); ?>;
//global variable
var userLat;
var userLng;
var acc;
if(!navigator.geolocation, jArray){
alert('Your Browser does not support HTML5 Geo Location. Please Use Newer Version Browsers');
}
navigator.geolocation.getCurrentPosition(success, error, jArray);
console.log(jArray);
function success(position, jArray)
{
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var accuracy = position.coords.accuracy;
document.getElementById("lat").value = latitude;
document.getElementById("lng").value = longitude;
document.getElementById("acc").value = accuracy;
//updating global variable with user's latitude longitude
userLat = latitude;
userLng = longitude;
acc = accuracy;
//console.log(userLat)
console.log(jArray);
//var ulat = $('#lat').val();
//var ulongi = $('#lng').val();
//call your distance function here i.e after success, then only there will be values.
//distance(ulat, userLng ,28.459768, 77.05169939999999,"K");
}
function error(err){
alert('ERROR(' + err.code + '): ' + err.message);
}
function distance(lat1, lon1, lat2, lon2, unit)
{
var radlat1 = Math.PI * lat1/180
var radlat2 = Math.PI * lat2/180
var radlon1 = Math.PI * lon1/180
var radlon2 = Math.PI * lon2/180
var theta = lon1-lon2
var radtheta = Math.PI * theta/180
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
dist = Math.acos(dist)
dist = dist * 180/Math.PI
dist = dist * 60 * 1.1515
if (unit=="K") { dist = dist * 1.609344 }
if (unit=="N") { dist = dist * 0.8684 }
console.log(dist)
return dist
}
</script>
let me know how i can store the latitude and longitude from the browser globally, Thanks