我正在致力于将 Google 的 Places API 集成到网络应用程序中。我已经能够成功地创建代码以允许用户使用 API 搜索地点并在应用程序中显示结果,这太棒了。
我一直无法弄清楚的是如何允许该应用程序的用户添加新地点。谷歌说的东西是可行的。他们在这里有一些文档 -
https://code.google.com/apis/maps/documentation/places/#adding_a_place
但是没有示例代码,我在编写 PHP 代码来实现添加调用时遇到了一些困难。
这是我到目前为止编写的代码。我在这里用 {your key} 替换了我的实际 API key 。
我不断收到格式错误的帖子错误 -
400。那是一个错误。 您的客户发出了格式错误或非法的请求。这就是我们所知道的。
<?php
function ProcessCurl($URL, $fieldString){ //Initiate Curl request and send back the result
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADERS, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('json'=>json_encode($fieldString)));
$resulta = curl_exec ($ch);
if (curl_errno($ch)) {
print curl_error($ch);
} else {
curl_close($ch);
}
echo $resulta;
}
$jsonpost = '{
"location": {
"lat": -33.8669710,
"lng": 151.1958750
},
"accuracy": 50,
"name": "Daves Test!",
"types": ["shoe_store"],
"language": "en-AU"
}';
$url = "https://maps.googleapis.com/maps/api/place/add/json?sensor=false&key={your key}";
$results = ProcessCurl ($url, $jsonpost);
echo $results."<BR>";
?>
最佳答案
您的代码存在一些问题。
首先,您将使用 CURLOPT_HTTPHEADER
,而实际上它是 CURLOPT_HTTPHEADER
(没有尾随的“S”)。该行应为:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
接下来,Google 不希望您传递参数名称,而只是一个值。另一件事是 $jsonpost
已经是 JSON,因此无需调用 json_encode
。该行应为:
curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldString);
有关更多信息,请查看 Google 文档:http://code.google.com/apis/maps/documentation/places/#adding_a_place .
您的完整代码,经过修复、测试和工作:
<?php
function ProcessCurl($URL, $fieldString){ //Initiate Curl request and send back the result
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
//curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldString);
$resulta = curl_exec ($ch);
if (curl_errno($ch)) {
print curl_error($ch);
} else {
curl_close($ch);
}
echo $resulta;
}
$jsonpost = '{
"location": {
"lat": -33.8669710,
"lng": 151.1958750
},
"accuracy": 50,
"name": "Daves Test!",
"types": ["shoe_store"],
"language": "en-AU"
}';
$url = "https://maps.googleapis.com/maps/api/place/add/json?sensor=false&key=";
$results = ProcessCurl ($url, $jsonpost);
echo $results."<BR>";
关于通过 API 向 Google Places 添加新地点的 PHP 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6481334/