Monday 31 January 2022

Thursday 27 January 2022

PHP Google GeoCoding Getting Latitude & Longitude

  
private function getGeoLocation($address)  
   {  
     try {  
       $url = 'https://maps.google.com/maps/api/geocode/json';  
       $address = str_replace(["'", '"'], " ", $address);  
       $address = str_replace([" ", " "], "+", $address);  
       $query_array = array(  
         'address' => $address,  
         'key' => env('GOOGLE_MAP_API_KEY')  
       );  
       $query = http_build_query($query_array);  
       $content = file_get_contents($url . '?' . $query);  
       $output = json_decode($content);  
       $result = [];  
       if ($output->status == "OK") {  
         $result['latitude'] = $output->results[0]->geometry->location->lat;  
         $result['longitude'] = $output->results[0]->geometry->location->lng;  
       }  
       return $result;  
     } catch (\Exception $ex) {  
       return [];  
     }  
   }  
Share:

Popular Posts

Recent Posts

Pages

Powered by Blogger.

About Me

My photo
For the past 10 years, I've been playing with codes using PHP, Java, Rails. I do this for a living and love new things to learn and the challenges that comes with it. Besides programming I love spending time with friends and family and can often be found together catching the latest movie or planning a trip to someplace I've never been before.