I'm facing issues getting value of a variable from another function. I'm trying to get the distance of the place from current position in google maps, but using Haversine Formula of calculating distance.
My HTML:
<p>
<script>
lat = "<?php echo $atm_row_data->latitude;?>";
lng = "<?php echo $atm_row_data->longitude;?>";
dist = getDistance(lat, lng);
document.write(dist);
</script>
</p>
My JavaScript:
var curPosition;
var lat, lng;
/**** get current position ****/
function getPosition() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showCurrentPosition);
} else {
alert('Geolocation is not supported by this browser.');
}
}
function showCurrentPosition(position) {
lat = position.coords.latitude;
lng = position.coords.longitude;
curPosition = new google.maps.LatLng(lat, lng);
console.log('curPosition: '+curPosition); <--- this works
}
/******** Haversine Formula of Getting Distance ********/
var rad = function(x) {
return x * Math.PI / 180;
};
function getDistance(lt, lg) {
console.log(curPosition); <--- this shows undefined
var p1 = curPosition;
var R = 6378137; // Earth’s mean radius in meter
var dLat = rad(lt - p1.lat());
var dLong = rad(lg - p1.lng());
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(rad(p1.lat())) * Math.cos(rad(lt)) *
Math.sin(dLong / 2) * Math.sin(dLong / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
if (d >= 1000)
return Math.round( (d / 1000) * 100) / 100 + "Km";
else
return Math.round( (d * 100) / 100) + "m";
};
/******** END Haversine Formula of Getting Distance ********/
Where am I going wrong?
Any help is appreciated...
showCurrentPosition, so thecurPositionremains undefined.curPositionin the beginning outside any functions.getPosition()is not called before callinggetDistance().