May I know how to get current user location and calculate distance between location B in kilometer?
I tried below codes but seems like does not work.
<?php
echo "<script type = 'text/javascript'>
function showPosition(){
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
});
} else {
alert(\"Sorry, your browser does not support HTML5 geolocation.\");
}
}
</script>";
$point1 = array("lat" => $latitude, "long" => $longitude);
$point2 = array("lat" => $row_Merchant['latitude'], "long" => $row_Merchant['longitude']);
$km = distanceCalculation($point1['lat'], $point1['long'], $point2['lat'], $point2['long']); // Calculate distance in kilometres (default)
echo "$km km";
?>
<?php
function distanceCalculation($point1_lat, $point1_long, $point2_lat, $point2_long, $unit = 'km', $decimals = 2)
{
// Calculate the distance in degrees
$degrees = rad2deg(acos((sin(deg2rad($point1_lat)) * sin(deg2rad($point2_lat))) + (cos(deg2rad($point1_lat)) * cos(deg2rad($point2_lat)) * cos(deg2rad($point1_long - $point2_long)))));
// Convert the distance in degrees to the chosen unit (kilometres, miles or nautical miles)
switch ($unit) {
case 'km':
$distance = $degrees * 111.13384; // 1 degree = 111.13384 km, based on the average diameter of the Earth (12,735 km)
break;
case 'mi':
$distance = $degrees * 69.05482; // 1 degree = 69.05482 miles, based on the average diameter of the Earth (7,913.1 miles)
break;
case 'nmi':
$distance = $degrees * 59.97662; // 1 degree = 59.97662 nautic miles, based on the average diameter of the Earth (6,876.3 nautical miles)
}
return round($distance, $decimals);
}
?>
How can I pass in value latitude and longitude in $point1 = array("lat" => $latitude, "long" => $longitude); so that I can calculate distance between user location and lcoation B?
Please help. Thank you.