简体   繁体   中英

Google Geocode with PHP

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

?>

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

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
}

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM