chr*_*ple 8 php google-maps-api-3
我正在努力将Google的Places API集成到网络应用中.我已经能够成功创建代码以允许用户使用API搜索地点并在应用程序中显示结果,这样很酷.
我无法弄清楚的是如何让应用程序的用户添加新的地方.谷歌说的东西是可行的.他们在这里有一些文件 -
https://code.google.com/apis/maps/documentation/places/#adding_a_place
但是没有示例代码,我在编写PHP代码以实现add调用时遇到了一些困难.
这是我到目前为止提出的代码.我在这里用{your key}替换了我的实际API密钥.
我一直收到错误的帖子错误 -
那是一个错误.您的客户发出了格式错误或非法的请求.我们知道的就这些.
<?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>";
?>
Run Code Online (Sandbox Code Playgroud)
您的代码存在一些问题.
首先,你CURLOPT_HTTPHEADERS
实际上是在使用它的时候CURLOPT_HTTPHEADER
(没有尾随的"S").该行应为:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
Run Code Online (Sandbox Code Playgroud)
接下来,Google不希望您传递参数名称,只是一个值.另一件事是$jsonpost
已经是JSON所以没有必要打电话json_encode
.该行应为:
curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldString);
Run Code Online (Sandbox Code Playgroud)
有关详情,请查看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>";
Run Code Online (Sandbox Code Playgroud)