Get Visitor Location using HTML5 Geolocation API and PHP

In this article, we will learn: How to get visitor geographical location using HTML geolocation API and then Calculate Distance Between Two Addresses using Google Maps API and PHP

1. We will use HTML5 geolocation API code(navigator.geolocation) that will prompt user to allow to know your location. 

The code below will perform this step:

<span class="location_distance" id="location_distance"></span>

<script> jQuery(document).ready(function(){ if(navigator.geolocation){ navigator.geolocation.getCurrentPosition(showLocation); }else{ alert('Geolocation is not supported by this browser.'); } });
function showLocation(position){ var latitude = position.coords.latitude; var longitude = position.coords.longitude; jQuery.ajax({ type:'POST', url:'index.php?option=com_componentName&task=properties.get_distance&latitude='+latitude+'&longitude='+longitude+'&item_latitude=<?=$item->latitude?>&item_longitude=<?=$item->latitude?>', data:'latitude='+latitude+'&longitude='+longitude+'&item_latitude=<?=$item->latitude?>&item_longitude=<?=$item->latitude?>&addressTo=<?=$item->address?>', success:function(msg){ if(msg){ jQuery("#location_distance").html(msg); }else{ jQuery("#location_distance").html('Not Available'); } } }); } </script>

2. Above code is making and ajax call. We will use component controller to perform calculate distance between two locations. So...

The Google Maps API Key is required to post HTTP request to Geocoding API and get response. Before getting started with the integration process, create an API key on the Google Cloud console.

  • Go to the Google Cloud console.
  • Select the project from the Project drop-down menu at the top. If you don’t have an existing project, create a new one.
  • In the left navigation pane, select the APIs & Services » Credentials.
  • In the Credentials page, select CREATE CREDENTIALS » API key.
  • The API key will be created and a dialog will appear with the newly created API key.
  • Navigate to the Library page from the left menu panel and make sure the Geocoding API is enabled.

Copy this API key for later use in the script on the Google Maps Geocoding API request.

PHP function code will be : 

public function get_distance(){
	//if latitude and longitude are submitted
	$latitude=JRequest::getVar('latitude');
	$longitude=JRequest::getVar('longitude');
	$item_latitude=JRequest::getVar('item_latitude');
	$item_longitude=JRequest::getVar('item_longitude');

	if(!empty($latitude) && !empty($longitude)){
	//send request and receive json data by latitude and longitude
	$url = 'https://maps.googleapis.com/maps/api/geocode/json?key=keyhere&latlng='.trim($latitude).','.trim($longitude).'&sensor=false';
	//   echo $url;
	$json = @file_get_contents($url);
	$data = json_decode($json);
	$status = $data->status;

	//if request status is successful
	if($status == "OK"){
		//get address from json data
		$location = $data->results[0]->formatted_address;
	}else{
		$location =  '';
	}

		/* ..................
		GET KM 
		-----------------------*/

		// Addresses between which distances will be calculated 
		$addressFrom    = $location;
		$addressTo      = JRequest::getVar('addressTo');

		// Format address string 
		$formatted_address_from = str_replace(array(' ','&'), '+', $addressFrom); 
		$formatted_address_to   = str_replace(array(' ','&'), '+', $addressTo); 

		// Geocoding API request with start address 
		$geocode_data_start = file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json?destinations=".urlencode($addressFrom)."&origins=".urlencode($addressTo)."&units=imperial&key=yourkey");
		$outputFrom = json_decode($geocode_data_start); 
		$distance_mile=(int)$outputFrom->rows[0]->elements[0]->distance->text;
		$distance_m=$outputFrom->rows[0]->elements[0]->distance->value;
		$distance_km=round(($distance_mile * 1.609344), 2);

		echo " $distance_km Km";exit;
	}
}

Need Joomla experts for development of custom Joomla Plugin, feel free to contact us Today