1

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;
    }

?>
solar411
  • 822
  • 1
  • 11
  • 27
  • 1
    Your script works for me, maybe the https-wrapper is not available in your environment( see: http://stackoverflow.com/questions/1975461/how-to-get-file-get-contents-work-with-https ) – Dr.Molle Aug 03 '15 at 18:44
  • Thanks. The wrapper was available but it ended up to be a proxy issue. Appreciate the help. – solar411 Aug 03 '15 at 20:56

3 Answers3

1

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;
Andrew Koper
  • 4,049
  • 5
  • 32
  • 41
0

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);
Community
  • 1
  • 1
solar411
  • 822
  • 1
  • 11
  • 27
0

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
}
Tony Dong
  • 2,987
  • 1
  • 25
  • 29