如果您不想使用Google API PHP客户端,可以使用原生的PHP函数和CURL库来发送请求和处理响应。下面是一个示例代码,演示了如何通过HTTP POST方法调用Google Geocoding API,并获取返回的JSON数据。
'1600 Amphitheatre Parkway, Mountain View, CA',
'key' => '您的API密钥'
);
// 将请求数据转换为URL编码的字符串
$data = http_build_query($data);
// 创建一个cURL资源
$ch = curl_init();
// 设置请求的URL和其他选项
curl_setopt($ch, CURLOPT_URL, 'https://maps.googleapis.com/maps/api/geocode/json');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 发送请求并获取响应
$response = curl_exec($ch);
// 关闭cURL资源
curl_close($ch);
// 处理响应
if ($response) {
$json = json_decode($response, true);
if ($json['status'] == 'OK') {
// 获取解析的结果
$results = $json['results'];
foreach ($results as $result) {
$formattedAddress = $result['formatted_address'];
$latitude = $result['geometry']['location']['lat'];
$longitude = $result['geometry']['location']['lng'];
echo "Formatted Address: $formattedAddress\n";
echo "Latitude: $latitude\n";
echo "Longitude: $longitude\n";
}
} else {
echo "Geocoding failed. Status: {$json['status']}\n";
}
} else {
echo "Failed to send request.\n";
}
?>
请注意,上述代码中的'您的API密钥'
需要替换为您自己的Google Geocoding API密钥。
这个示例代码使用了curl_init()
、curl_setopt()
和curl_exec()
等函数来发送HTTP POST请求,并使用json_decode()
函数解析返回的JSON数据。然后,您可以根据需要处理和使用解析的结果。
但是,请注意,使用Google API PHP客户端可以更方便地与Google API进行交互,并提供了许多其他功能和工具。所以,如果可能的话,建议使用Google API PHP客户端。