# Sample Code: Geocoding and Related



## Disparia (Mar 8, 2008)

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(
			$obj->Result->Latitude,
			$obj->Result->Longitude,
			$obj->Result->attributes()->precision);
	} else {
		return false;
	}
}

#Usage
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);
	return $array;
}

#Usage
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 = 2 * M_PI; }
	return acos(sin($lat2) * sin($lat1) + cos($lat2) * cos($lat1) * cos($a)) * 3958;
}

#Usage
$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 (Mar 8, 2008)

Thanks Jiz 

Those are actually some handy little functions.


----------

