forked from TheRestartProject/restarters.net
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeocoder.php
More file actions
57 lines (44 loc) · 1.71 KB
/
Geocoder.php
File metadata and controls
57 lines (44 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?php
namespace App\Helpers;
class Geocoder
{
public function __construct()
{
}
private function googleKey()
{
// We have this so that we can change the key in testing.
return config('GOOGLE_MAPS_BACKEND_KEY') ?? env('GOOGLE_MAPS_BACKEND_KEY');
}
public function geocode($location)
{
if ($location != 'ForceGeocodeFailure') {
$json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($location).'&key='.$this->googleKey());
if ($json) {
$res = json_decode($json);
if ($res && $res->results && count($res->results)) {
$decoded = json_decode($json)->results[0];
$latitude = $decoded->{'geometry'}->{'location'}->lat;
$longitude = $decoded->{'geometry'}->{'location'}->lng;
foreach ($decoded->{'address_components'} as $component) {
if ($component->types && count($component->types) && $component->types[0] === 'country') {
$country_code = $component->short_name;
}
}
return [
'latitude' => $latitude,
'longitude' => $longitude,
'country_code' => $country_code,
];
}
}
}
return false;
}
public function reverseGeocode($lat, $lng)
{
$json = file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lng&key=".$this->googleKey());
$decoded = json_decode($json)->results[0];
return $decoded;
}
}