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

Sample Code: Geocoding and Related

Aug 10, 2007
4,064 (1.07/day)
Geneva, FL, USA
Processor Intel i5-6600
Motherboard ASRock H170M-ITX
Cooling Cooler Master Geminii S524
Memory G.Skill DDR4-2133 16GB (8GB x 2)
Video Card(s) Gigabyte R9-380X 4GB
Storage Samsung 950 EVO 250GB (mSATA)
Display(s) LG 29UM69G-B 2560x1080 IPS
Case Lian Li PC-Q25
Audio Device(s) Realtek ALC892
Power Supply Seasonic SS-460FL2
Mouse Logitech G700s
Keyboard Logitech G110
Software Windows 10 Pro
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 {
		return false;

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;

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;

$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 :)