Reputation: 852
I'm trying to get latitude and longitude from Google's Geocode API. The $url
I'm using outputs the correct JSON however something in my script isn't working correctly. It's not outputting the $lati
& $longi
variables. Please check see the script below:
PHP:
<?php
$address = 'Tempe AZ';
$address = urlencode($address);
$url = "https://maps.google.com/maps/api/geocode/json?sensor=false&address={$address}";
$resp_json = file_get_contents($url);
$resp = json_decode($resp_json, true);
if ($resp['status'] == 'OK') {
// get the important data
$lati = $resp['results'][0]['geometry']['location']['lat'];
$longi = $resp['results'][0]['geometry']['location']['lng'];
echo $lati;
echo $longi;
} else {
return false;
}
?>
Upvotes: 1
Views: 8220
Reputation: 7199
I brought in the Guzzle http package at the top of my Laravel file/class: use GuzzleHttp\Client;
Then, to take an address and convert it to lat and lng to save with PHP/Laravel and Google Maps API, I added this code in my save() method:
// get latitude and longitude of address with Guzzle http package and Google Maps geocode API
$client = new Client(); // GuzzleHttp\Client
$baseURL = 'https://maps.googleapis.com/maps/api/geocode/json?address=';
$addressURL = urlencode(request('street')) . ',' . urlencode(request('city')) . ',' . urlencode(request('state')) . '&key=' . env('GOOGLE_MAPS_API_KEY');
$url = $baseURL . $addressURL;
$request = $client->request('GET', $url);
$response = $request->getBody()->getContents();
$response = json_decode($response);
$latitude = $response->results[0]->geometry->location->lat;
$longitude = $response->results[0]->geometry->location->lng;
Upvotes: 1
Reputation: 1
Your script works for me too. Maybe you will get an error calling:
$resp_json = file_get_contents($url);
.
If that happens you should do this:
$resp_json = @file_get_contents($url);
if ($resp_json === FALSE) {
///logic for exception
} else {
///do your logic hear
}
Upvotes: 0
Reputation: 852
It turned out to be a proxy issue. This thread helped: Using proxy with file_get_contents
Added this:
$opts = array(
'http' => array(
'method' => "GET",
'header' => "Accept-language: en\r\n".
"Cookie: foo=bar\r\n",
'proxy' => 'tcp://proxy.proxy.com:8080',
)
);
$context = stream_context_create($opts);
// open the file using the HTTP headers set above
$file = file_get_contents($url, false, $context);
Upvotes: 0