1. Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

Sample Code: Geocoding and Related

Discussion in 'Programming & Webmastering' started by Jizzler, Mar 8, 2008.

  1. Jizzler


    Aug 10, 2007
    4,038 (1.08/day)
    Thanks Received:
    Geneva, FL, USA
    Couple functions I wrote up for my last job which involved booking demonstrators at grocery stores (the little old ladies that give out samples).

    function ReturnCoords($address) {
    $url "http://api.local.yahoo.com/MapsService/V1/geocode?appid=abc&location=".urlencode($address);
    $xml = @file_get_contents($url);
        if (
    $xml) {
    $obj = new SimpleXMLElement($xml);
            return array(
        } else {

    list($lat$lon$pre) = ReturnCoords('4250 ALAFAYA TRL, OVIEDO, FL 32765');
    Will return the latitude, longitude and precision from the address given. Note that Yahoo returns string precision levels like "address", "street", "zip", "city", etc - not a numeric scale. Yahoo allows about 5000 calls a day, which is why I use them vs other sites with much lower call per day limits.

    If you host doesn't have SimpleXML loaded, could use the XML Parser functions.

    function CoordinateBox($lat$lon$range) {
    $latmile 69.172;
    $array[0] = $lat $range $latmile;
    $array[1] = $lat - ($array[0] - $lat);
    $array[2] = $lon $range / (cos($array[1] * M_PI 180) * $latmile);
    $array[3] = $lon - ($array[2] - $lon);

    list($maxlat$minlat$maxlon$minlon) = CoordinateBox($lat$lon$range);
    Can quickly pull a set of people from a database within a "box" of the main point - in my case, a store like Winn-Dixie or Kroger. EX: "SELECT * FROM Users WHERE Latitude BETWEEN $maxlat AND $minlat AND Longitude BETWEEN $maxlon AND $minlon";

    function DistanceCalc($lat1$lon1$lat2$lon2) {
    $lat1 $lat1 180 M_PI;
    $lon1 $lon1 180 M_PI;
    $lat2 $lat2 180 M_PI;
    $lon2 $lon2 180 M_PI;
    $a $lon1 $lon2;
        if (
    $a 0) { $a = -$a; }
        if (
    $a M_PI) { $a M_PI; }
    acos(sin($lat2) * sin($lat1) + cos($lat2) * cos($lat1) * cos($a)) * 3958;

    $miles DistanceCalc($lat1$lon1$lat2$lon2);
    Since people in the corner of the returned "box" are outside of the range, I check everyone's distance ($miles < $range) from the main point. Since I want this number for sorting purposes anyway, it's a not a waste of function calls.

    Might be useful for someone or at least help out Kriej and his mission :)
    Kreij says thanks.
    10 Year Member at TPU Crunching for Team TPU
  2. Kreij

    Kreij Senior Monkey Moderator Staff Member

    Feb 6, 2007
    13,817 (3.54/day)
    Thanks Received:
    Cheeseland (Wisconsin, USA)
    Thanks Jiz :toast:

    Those are actually some handy little functions.
    10 Year Member at TPU

Currently Active Users Viewing This Thread: 1 (0 members and 1 guest)