Julian Lannigan

PHP Geocoding { 0 }

I wrote this cool little function that will use cURL to get the latitude and longitude of the given location.  This can be useful for locating stores in the same area as the given location.

To see this function in action check out this page.  Now, you won’t be able to your view your entered latitude and longitude, but if you live close to a city put in just your zip code and you should be able to see some stores.  TIDBIT: If you enter just “la” without the quotes, the Yahoo Geocoding API will recognize this as Los Angeles, which I thought was pretty cool.  Also note, that this API also recognizes international addresses.

Visit the Yahoo Geocoding API page for more information on the capabilities and responses of the service.  Also, that page has a link for you to get your own application id.

function getGeoLocation($location)
{
    //Yahoo Developer API Stuff
    $appid = "YD-9G7bey8_JXxQP6rxl.fBFGgCdNjoDMACQA--";
    $appurl = "http://local.yahooapis.com/MapsService/V1/geocode?appid=%s&location=%s";

    $url = sprintf($appurl, $appid, urlencode($location)); //convert location to a safe url param

    //Setup curl object and execute
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($curl);

    //Process response from Yahoo servers
    if (($error = curl_errno($curl)) > 0)
    {
        $error = curl_errno($curl);
    }

    //Try to convert XML response into an object
    try
    {
        $req = new SimpleXMLElement($result);
    }
    catch (Exception $e)
    {
        return -1;
    }

    //Return converted XML object or false if anything went wrong
    return ($error != 0) ? 0 : $req;
}

Now as some of you may know, there are a lot of ways to write the same thing. So, I wrote the above function after I wrote the next function, just because I wanted to experiment some with cURL. Here is another way to write same function only this way doesn’t use cURL or SimpleXML and this function outputs a native php array rather than the structure data object. Check it out.

function getGeoLocation($location)
{
    //Yahoo Developer API Stuff
    $appid = "YD-9G7bey8_JXxQP6rxl.fBFGgCdNjoDMACQA--";
    $appurl = "http://local.yahooapis.com/MapsService/V1/geocode?appid=%s&location=%s&output=php";

    $url = sprintf($appurl, $appid, urlencode($location)); //convert location to a safe url param

    $result = file_get_contents($url);

    if ($result == false)
    {
        return false;
    }

    return unserialize($result);
}

This function may work better for some of you that are using servers that do not have cURL or SimpleXML. To answer the question of which function is faster, I couldn’t answer that because I haven’t done any benchmarking tests.

Hope you enjoy!

Be Sociable, Share!

Leave a Reply