如何用PHP SDK+API Key调用无自定义索引的AWS Location Place Index?
用PHP SDK无自定义Place Index调用AWS Location Place Index的解决方案
目前AWS PHP SDK的LocationService客户端确实还未适配v2版本的无索引API(截至2025年7月),不过可以通过以下两种无需Composer补丁的方式实现需求:
方法1:使用通用AWS客户端直接发送HTTP请求
绕开LocationService的特定客户端,用AWS通用客户端构造请求直接调用v2端点,无需依赖SDK内置的API定义:
use Aws\Client; // 初始化通用AWS客户端 $client = new Client([ 'region' => 'us-west-2', // 替换为你的服务区域 'version' => 'latest', ]); // 调用v2搜索文本端点(地址转GPS) $response = $client->post( "https://places.geo.{$client->getRegion()}.amazonaws.com/v2/search-text", [ 'headers' => [ 'X-Amz-API-Key' => 'YOUR_API_KEY', // 替换为你的API Key 'Content-Type' => 'application/json', ], 'json' => [ 'Text' => '1600 Pennsylvania Ave NW, Washington, DC', // 要搜索的地址 'MaxResults' => 5, // 可选参数:返回结果数量 'Country' => ['US'] // 可选参数:限定国家范围 ], ] ); // 解析返回结果 $searchResults = json_decode($response->getBody(), true); print_r($searchResults);
如果需要GPS转地址,直接替换端点为/v2/reverse-geocode,调整请求参数即可,比如传入Position数组(纬度+经度)。
方法2:自定义SDK API定义文件
复制SDK内置的API定义文件到本地,添加v2端点的定义,让LocationClient加载本地修改后的配置:
- 复制并修改API定义
找到SDK安装目录下的vendor/aws/aws-sdk-php/src/LocationService/Api/2020-11-19/api-2.json,复制到项目目录后,添加v2版本的操作定义。示例新增片段:
"operations": { // 保留原有操作 "SearchTextV2": { "http": { "method": "POST", "requestUri": "/v2/search-text" }, "input": { "shape": "SearchTextV2Request" }, "output": { "shape": "SearchTextV2Response" } } }, "shapes": { // 新增请求响应结构 "SearchTextV2Request": { "type": "structure", "required": ["Text"], "members": { "Text": {"type": "string"}, "ApiKey": {"type": "string", "location": "header", "name": "X-Amz-API-Key"}, "MaxResults": {"type": "integer"}, "Country": {"type": "list", "member": {"type": "string"}} } }, "SearchTextV2Response": { "type": "structure", "members": { "Results": {"type": "list", "member": {"shape": "SearchResult"}}, "Summary": {"shape": "SearchSummary"} } } }
- 加载自定义API初始化客户端
use Aws\LocationService\LocationServiceClient; use Aws\Api\ApiProvider\FileProvider; // 指定本地修改后的API文件路径 $localApiProvider = new FileProvider('/path/to/your/modified/api-2.json'); $client = new LocationServiceClient([ 'region' => 'us-east-1', 'version' => '2020-11-19', 'api_provider' => $localApiProvider, 'credentials' => false, // 使用API Key无需IAM凭证 ]); // 调用自定义的v2搜索方法 $result = $client->searchTextV2([ 'Text' => '123 Main St', 'ApiKey' => 'YOUR_API_KEY', 'MaxResults' => 3 ]); print_r($result->toArray());
这种方法适合需要保留LocationService客户端风格调用的场景,但需要自行维护API定义的同步。
内容的提问来源于stack exchange,提问作者Jan Klan
相关产品推荐
相关产品推荐

