Using Google Geolocate API to retrieve Lat/Lon by Address in PHP

PHP

If we are using something like the Leaflet API, we will need to return an array of lat/long in order to create markers and do other fun things. We can use the following PHP to take an Address, City, Zip, and process it through the Geolocate API and retrieve the corresponding lat/long.

        //  Update the Long/Lat for the Maps Integration
function geolocate($address,$city,$zip) {
        $_address   = str_replace(' ',',', $address);
        $_city      = str_replace(' ',',', $city);  
        $_zip       = str_replace(' ',',', $zip); 

        $Address    = $_address.',+'.$_city.',+'.$_zip;

        $Address = urlencode($Address);
        $request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$Address."&sensor=true";
        $xml = simplexml_load_file($request_url) or die("url not loading");
        $status = $xml->status;
        if ($status=="OK") {

            $_Lat = $xml->result->geometry->location->lat;
            $_Lon = $xml->result->geometry->location->lng;

            $Lat = json_encode($_Lat);
            $Lon = json_encode($_Lon);

            $Lat = json_decode($Lat,true);
            $Lon = json_decode($Lon,true);

            $Lat = $Lat[0];
            $Lon = $Lon[0];
            return array($Lat,$Lon);

        } else { 
            return; 
        }
}