通过Google Places API解析地址

时间:2017-04-03 15:53:32

标签: php google-maps google-api google-places-api

我有一个巨大的(50k)数据库,其地址如

12340 Via Moura, San Diego, CA, United States
17029 Avenida Cordillera, San Diego, CA, United States
3324 Sandleheath, Sarasota, FL 34235, USA

他们使用google Places Autocomplete js api自动完成,然后存储在db中。 现在,我需要获得这些地址的不同部分statecityzip ...等。 是否有可能与一些谷歌API? 有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我找到了解决方案。 需要对google places API进行两次API调用。 首先通过完整地址调用PLACE_ID,然后通过PLACE_ID获取有关地址的所有数据。

        $params = [
            'key' => env('GOOGLE_API_KEY'),
            'query' => 'FULL_ADDRESS',
            'types' => 'address'
        ];
        $guzzle_client = new Client();
        $res = $guzzle_client->request('GET', 'https://maps.googleapis.com/maps/api/place/textsearch/json?parameters',
            [
                'query' => $params
            ]
        );

        $prediction = json_decode($res->getBody(), true);
        if ($prediction['status'] == 'OK') {
            $paramsID = [
                'key' => env('GOOGLE_API_KEY'),
                'placeid' => $prediction['results'][0]['place_id'],
            ];
            $guzzle_clientID = new Client();
            $resID = $guzzle_clientID->request('GET', 'https://maps.googleapis.com/maps/api/place/details/json',
                [
                    'query' => $paramsID
                ]
            );

            $predictionID = json_decode($resID->getBody(), true);

            $address_components = $predictionID['result']['address_components'];
            $address = [];
            foreach ($address_components as $component) {
                switch ($component['types'][0]) {
                    case 'street_number':
                        $address['street_number'] = $component['short_name'];
                        break;
                    case 'route':
                        $address['street_name'] = $component['short_name'];
                        break;
                    case 'locality':
                        $address['city'] = $component['short_name'];
                        break;
                    case 'administrative_area_level_1':
                        $address['state'] = $component['short_name'];
                        break;
                    case 'postal_code':
                        $address['zip'] = $component['short_name'];
                        break;
                }
            }
            $addresses[]= $address;
        } else {
            dd('Not found place');
        }