简体   繁体   中英

Parse addresses through Google Places API

I have a huge(50k) db with addresses like

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

They were autocompleted with google Places Autocomplete js api and then stored in db. Now I need to get distinct parts state , city , zip ... etc of these addresses. Is it possible to do with some google of API? Any ideas?

I found a solution. Need to do two API calls to google places API. First call to get PLACE_ID by full address, second one get all data about address by 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');
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM