Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Google Geocoding
<?php
/*
Author: Gkiokan Sali
Web: https://gkiokan.net
Date: 11.08.2020
Comments:
Use Google Geocoding API in Laravel
but it can be extracted to any other PHP Application, too.
It has also helper functions that can help others, too.
*/
namespace Gkiokan\CCP\Http\Controllers\Google;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Illuminate\Support\Arr;
use Http;
class GeocodingController extends Controller
{
protected $uri = "https://maps.googleapis.com/maps/api/geocode/json?";
protected $key = '';
public $requestURL = null;
public $response = null;
public function __construct(){
}
public function request($data=[]){
$params = array_merge(['key' => env('GOOGLE_MAPS_API_KEY', null)], $data);
$response = Http::get( $this->uri, $params);
$response = json_decode($response->body(), true);
return $response;
}
public function getAddress($response=[]){
$ac = Arr::get($response, 'results.0.address_components', []);
// predefine final variable
$address = [
'street' => '',
'nr' => '',
'address' => '',
'city' => '',
'postal_code' => '',
'country' => '',
'formatted' => Arr::get($response, 'results.0.formatted_address'),
];
// loop though address_components
foreach($ac as $item):
$value = Arr::get($item, 'long_name');
$type = Arr::get($item, 'types')[0];
switch ($type):
case 'street_number':
$address['nr'] = $value;
$address['address'] = strlen($address['address']) == 0 ? ($address['address'] . ' ' . $value) : ($value . $address['address']);
break;
case 'route':
$address['street'] = $value;
$address['address'] = strlen($address['address']) == 0 ? ($address['address'] . ' ' . $value) : ($value . $address['address']);
break;
case 'locality':
$address['city'] = $value;
break;
case 'postal_code':
$address['postal_code'] = $value;
break;
case 'country':
$address['country'] = $value;
break;
endswitch;
endforeach;
return $address;
}
public function getLocation($response=[]){
return Arr::get($response, 'results.0.geometry.location');
}
public function getStatus($response=[]){
return Arr::get($response, 'status', 'STATUS_NOT_FOUND');
}
public function getGeoLocation(Request $r){
$params = [];
if($r->input('q'))
$params['address'] = $r->input('q');
if($r->input('latlng'))
$params['latlng'] = $r->input('latlng');
$response = $this->request($params);
$location = $this->getLocation($response);
$status = $this->getStatus($response);
$address = $this->getAddress($response);
return response()->json([
// 'all' => $r->all(), // debug only
'response' => $response,
'address' => $address,
'location' => $location,
'status' => $status,
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment