Почему я получаю сообщение об ошибке «Для этой службы требуется ключ API»? - PullRequest
0 голосов
/ 05 июня 2018

Я пытаюсь отправить запрос на публикацию в API мест Google, используя следующий код PHP, но я получаю сообщение об ошибке

string (141) "{" error_message ":" Для этой службы требуется ключ API."," html_attributions ": []," results ": []," status ":" REQUEST_DENIED "}"

<?php
include_once 'configuration.php';

$url = 'https://maps.googleapis.com/maps/api/place/textsearch/json';
$data = array('query' => 'restaurants in Sydney', 'key' => API_KEY);

$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }

var_dump($result);

В чем проблема?

1 Ответ

0 голосов
/ 05 июня 2018

Как описано в документации текстового поиска , параметр должен быть в методе GET.Вы указали его как POST.

A Text Search request is an HTTP URL of the following form:

    https://maps.googleapis.com/maps/api/place/textsearch/output?parameters

...

Certain parameters are required to initiate a search request. As is standard in URLs, all parameters are separated using the ampersand (&) character.

Попробуйте использовать этот фрагмент:

<?php
include_once 'configuration.php';

$url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=' . urlencode('restaurants in Sydney') . '&key=' . API_KEY;

$result = file_get_contents($url);
if ($result === FALSE) { /* Handle error */ }

var_dump($result);

Чтобы использовать параметр массива, измените $url на:

$data = array('query' => 'restaurants in Sydney', 'key' => API_KEY);
$url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?' . http_build_query($data);
...