HwapX

CEP - Google Maps Api

Feb 16th, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.05 KB | None | 0 0
  1. <?php
  2.  
  3. function getCoordenadasCep($cep, $precisao_minima = 1, $precisao = 8) {
  4.     if($cep == '00000000')
  5.         return null;
  6.  
  7.     $service_url = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false&components=country:BR';
  8.  
  9.     $referencia = $cep;
  10.  
  11.     for ($idx = 7; $idx >= $precisao; $idx--) {
  12.         $referencia[$idx] = 0;
  13.     }
  14.  
  15.     $result = DB::q('SELECT * FROM default_ceps c WHERE c.cep = ?s AND c.precisao > 0', $referencia)->fetch(PDO::FETCH_ASSOC);
  16.  
  17.     if($result) {
  18.         return $result;
  19.     }
  20.  
  21.     $masked   = preg_replace('/(\d{5})(\d{3})/', "$1-$2", $referencia);
  22.     $url      = sprintf($service_url, $masked);
  23.     $response = file_get_contents($url);
  24.     $data     = json_decode($response, true);
  25.     $types    = isset($data['results'][0]['address_components'][0]['types']) ? (array)$data['results'][0]['address_components'][0]['types'] : array();
  26.  
  27.     if(!in_array('postal_code', $types) && !in_array('postal_code_prefix', $types)) {
  28.         $data = null;
  29.  
  30.         if($precisao > $precisao_minima) {
  31.             sleep(1);
  32.             $data = getCoordenadasCep($cep, $precisao_minima, $precisao - 1);
  33.  
  34.             if($data) {
  35.                 DB::x('REPLACE INTO default_ceps(cep, latitude, longitude, precisao, referencia) VALUES(?s, ?f, ?f, ?i, ?s)',
  36.                       $referencia, $data['latitude'], $data['longitude'], $data['precisao'], $data['referencia']);
  37.             }
  38.         }
  39.  
  40.         return $data;
  41.     }
  42.  
  43.     if(!isset($data['results'][0]['geometry']['location'])) {
  44.         return null;
  45.     }
  46.  
  47.     $location = $data['results'][0]['geometry']['location'];
  48.  
  49.     DB::x('REPLACE INTO default_ceps(cep, latitude, longitude, precisao, referencia) VALUES(?s, ?f, ?f, ?i, ?s)',
  50.           $referencia, $location['lat'], $location['lng'], 8, $referencia);
  51.  
  52.     return array(
  53.             'cep'       => $cep,
  54.             'latitude'  => $location['lat'],
  55.             'longitude' => $location['lng'],
  56.             'precisao'  => $precisao,
  57.             'referencia'=> $referencia
  58.         );
  59. }
Add Comment
Please, Sign In to add comment