Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function getCoordenadasCep($cep, $precisao_minima = 1, $precisao = 8) {
- if($cep == '00000000')
- return null;
- $service_url = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false&components=country:BR';
- $referencia = $cep;
- for ($idx = 7; $idx >= $precisao; $idx--) {
- $referencia[$idx] = 0;
- }
- $result = DB::q('SELECT * FROM default_ceps c WHERE c.cep = ?s AND c.precisao > 0', $referencia)->fetch(PDO::FETCH_ASSOC);
- if($result) {
- return $result;
- }
- $masked = preg_replace('/(\d{5})(\d{3})/', "$1-$2", $referencia);
- $url = sprintf($service_url, $masked);
- $response = file_get_contents($url);
- $data = json_decode($response, true);
- $types = isset($data['results'][0]['address_components'][0]['types']) ? (array)$data['results'][0]['address_components'][0]['types'] : array();
- if(!in_array('postal_code', $types) && !in_array('postal_code_prefix', $types)) {
- $data = null;
- if($precisao > $precisao_minima) {
- sleep(1);
- $data = getCoordenadasCep($cep, $precisao_minima, $precisao - 1);
- if($data) {
- DB::x('REPLACE INTO default_ceps(cep, latitude, longitude, precisao, referencia) VALUES(?s, ?f, ?f, ?i, ?s)',
- $referencia, $data['latitude'], $data['longitude'], $data['precisao'], $data['referencia']);
- }
- }
- return $data;
- }
- if(!isset($data['results'][0]['geometry']['location'])) {
- return null;
- }
- $location = $data['results'][0]['geometry']['location'];
- DB::x('REPLACE INTO default_ceps(cep, latitude, longitude, precisao, referencia) VALUES(?s, ?f, ?f, ?i, ?s)',
- $referencia, $location['lat'], $location['lng'], 8, $referencia);
- return array(
- 'cep' => $cep,
- 'latitude' => $location['lat'],
- 'longitude' => $location['lng'],
- 'precisao' => $precisao,
- 'referencia'=> $referencia
- );
- }
Add Comment
Please, Sign In to add comment