PHP geocode an address using Google

In order to calculate distance between two points on a map you first need to have the Latitude and Longitude of your two locations.  This snippet of code is one that I am using when a user registers their address in the sign up process.

It seemed much more efficient to do this geocoding once at registration and store the values in a database rather than request the data with every request the user makes

  $googleMapsBase = "";

  // Determines whether google maps will use the GPS sensor or not 
  // (REQUIRED: true / false)
  $sensorStatus = "false"; 

  $address = "1801 South 18th Street, Lafayette, IN, 47905";
  // Replace spaces in the address with +
  $address = str_replace(' ', '+', $address);

  $geocode = $googleMapsBase.$address."&sensor=$sensorStatus";

  $json = file_get_contents($geocode);
  $obj = json_decode($json);

  try {
    if(count($obj->results) > 0){
      echo "Latitude: ".$obj->results[0]->geometry->location->lat;
      echo ", Longitude: ".$obj->results[0]->geometry->location->lng;
      throw new Exception("No results found.", 1);
  } catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";