Showing posts with label city and state using the Google Geocoding API. Show all posts
Showing posts with label city and state using the Google Geocoding API. Show all posts

Wednesday, 31 July 2013

PHP Class to find out country,city and state using the Google Geocoding API

This is a simple class which uses the the Google Geocoding API to find out a location information based on the zip code. You will get the following using this class:
  • City
  • State
  • Country
  • Longitude
  • Latitude

NOTE:

- Here the backdrop is some of the countries zip codes  are same. so if we pass only zip code then it returns any one of the matching country details.

- So better we need to pass city with zip code. it results accurate country details.

- For example we need to pass ' 625106,Madurai '

Example:

include 'GoogleAddressLookup.php';
$zipCode = 625106; // 625106,Madurai for accurate result
$lookup = new GoogleAddressLookup();
$lookup->setZipCode($zipCode);
echo 'City: ' . $lookup->getCity() . '('. $lookup->getCityShortName().')<br>';
echo 'State: ' . $lookup->getState() . '('. $lookup->getStateShortName().')<br>';
echo 'Country: ' . $lookup->getCountry() . '('. $lookup->getCountryShortName().')<br>';
echo 'LAT: ' . $lookup->getLatitude().'-- LNG: ' . $lookup->getLongitude();


GoogleAddressLookup.php

<?php
/**
 * This class can be used to lookup city/state/country using zip code in Google Geo Lookup service.
 * This class uses the JSON API provided by Google Geo Lookup.
 *
 * @author Mohammad Sajjad Hossain
 * @version 1.0
 */
class GoogleAddressLookup{
    /**
     * Response
     * @var array
     */
    private $response;

    /**
     * Constructor
     */
    public function __construct(){
        $this->initialize();
    }

    /**
     * Initialize variables
     */
    private function initialize(){
        $this->response = array(
            'zip_code' => '',
            'state' => '',
            'state_short' => '',
            'city' => '',
            'city_short' => '',
            'country' => '',
            'country_short' => '',
            'latitude' => '',
            'longitude' => '',
            'raw_response' => ''
        );
    }

    /**
     * Sets Zup Code
     * @param int $zipCode
     */
    public function setZipCode($zipCode){
        $this->response['zip_code'] = $zipCode;

        $this->processResponse();
    }

    /**
     * Returns City full name
     *
     * @return string
     */
    public function getCity(){
        return $this->response['city'];
    }

    /**
     * Returns City short name
     *
     * @return string
     */
    public function getCityShortName(){
        return $this->response['city_short'];
    }

    /**
     * Returns State full name
     *
     * @return string
     */
    public function getState(){
        return $this->response['state'];
    }

    /**
     * Returns State short name
     *
     * @return string
     */
    public function getStateShortName(){
        return $this->response['state_short'];
    }

    /**
     * Returns Country full name
     *
     * @return string
     */
    public function getCountry(){
        return $this->response['country'];
    }

    /**
     * Returns Country short name
     *
     * @return string
     */
    public function getCountryShortName(){
        return $this->response['country_short'];
    }

    /**
     * Returns Latitude
     *
     * @return int
     */
    public function getLatitude(){
        return $this->response['latitude'];
    }

    /**
     * Returns Longitude
     *
     * @return int
     */
    public function getLongitude(){
        return $this->response['longitude'];
    }

    /**
     * Makes call to the API
     */
    private function makeCall(){
        if($this->response['zip_code']){
            $url = "http://maps.googleapis.com/maps/api/geocode/json?address={$this->response['zip_code']}&sensor=true";

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_VERBOSE, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
            curl_setopt($ch, CURLOPT_URL, $url);

            $this->response['raw_response'] = curl_exec($ch);
        }
    }

    /**
     * Processes the response received
     */
    private function processResponse(){
        $this->makeCall();

        if($this->response['raw_response']){
            $result = json_decode($this->response['raw_response']);

            if($result->status == 'OK'){
                if(!empty($result->results[0]->address_components)){
                    foreach($result->results[0]->address_components as $add_comp){
                        if(in_array('locality', $add_comp->types)){
                            $this->response['city'] = $add_comp->long_name;
                            $this->response['city_short'] = $add_comp->short_name;
                        }
                        elseif (in_array('administrative_area_level_1', $add_comp->types)) {
                            $this->response['state'] = $add_comp->long_name;
                            $this->response['state_short'] = $add_comp->short_name;
                        }
                        elseif (in_array('country', $add_comp->types)) {
                            $this->response['country'] = $add_comp->long_name;
                            $this->response['country_short'] = $add_comp->short_name;
                        }
                    }
                }

                if(!empty($result->results[0]->geometry)){
                    $this->response['longitude'] = $result->results[0]->geometry->location->lng;
                    $this->response['latitude'] = $result->results[0]->geometry->location->lat;
                }
            }
        }
    }
}