Skip to content

Instantly share code, notes, and snippets.

@drmmr763
Created July 3, 2014 20:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drmmr763/aa1db816dfd5cebc4349 to your computer and use it in GitHub Desktop.
Save drmmr763/aa1db816dfd5cebc4349 to your computer and use it in GitHub Desktop.
Geocoder
<?php
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();
// latlng
$latitude = JRequest::getString('tbl_locations___lat');
$longitude = JRequest::getString('tbl_locations___long');
// address
$addressString = compileAddressString();
// geo response
$geoResponse = getGeo($addressString);
// pure latlng object
$latlng = getLatLng($geoResponse);
// set the fields and let this continue on it's way
setLatLngFields($latlng);
function getLatLng($geoResponse)
{
$latlng = $geoResponse;
$location = $latlng->results[0]->geometry->location;
// for some reason this is blank so exit early
if ($location == '' || $location === false)
{
return false;
}
return $location;
}
function compileAddressString()
{
$address = JRequest::getString('tbl_locations___location_address');
$city = JRequest::getString('tbl_locations___location_city');
$state = JRequest::getString('tbl_locations___location_state');
$postcode = JRequest::getString('tbl_locations___location_zip');
$country = JRequest::getString('tbl_locations___location_country');
// add all our parts up
$compileAddress = array($address, $city, $state, $postcode, $country);
// google friendly version
// ex: 211+washington+street,new+smyrna+beach,fl,32168,united+states
$geoFriendlyAddress = implode(',', $compileAddress);
$geoFriendlyAddress = str_replace(' ', '+', $geoFriendlyAddress);
// if we don't have a complete string we should return false
if ($geoFriendlyAddress == '')
{
return false;
}
// return the string version of our address
return urlencode($geoFriendlyAddress);
}
function getGeo($address)
{
$googleGeocodeUrl = 'https://maps.googleapis.com/maps/api/geocode/json?';
$requestUrl = $googleGeocodeUrl . 'sensor=false&address=' . $address;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $requestUrl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$contents = json_decode(curl_exec($curl));
curl_close($curl);
if (! $contents)
{
return false;
}
if ($contents->status != 'OK')
{
return false;
}
return $contents;
}
function setLatLngFields($latlng)
{
$db = JFactory::getDbo();
$recordID = JRequest::getInt('tbl_locations___id');
$query = 'UPDATE tbl_locations SET tbl_locations.lat="' . $latlng->lat . '", tbl_locations.long="' . $latlng->lng . '" WHERE id=' . $recordID;
$db->setQuery($query);
$result = $db->query();
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment