Friday, May 29, 2015

How to get Latitude & Longitude using zipcode in php?

Get Latitude & Longitude:

It is a very simple way to get latitude & longitude using zipcode in php.
For this you have to use google api's.
Here is a function for doing this:
public function getLatLng($zip)
    {
        $request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=$zip&sensor=true";
        $xml = simplexml_load_file($request_url) or die("url not loading");
        $status = $xml->status;
        $lat = $lng = 0;
        if ($status == "OK") {
            $lat = $xml->result->geometry->location->lat;
            $lng = $xml->result->geometry->location->lng;
        }
        $loc = array('lat' => $lat, 'lng' => $lng);
        return $loc;
    }
Here $zip is a zipcode variable. It will return a array consisting of latitude & longitude.
Thanks.

No comments:

Post a Comment