Transforming an address into Latitude and Longitude using PHP and curl

T

Step 2 - Construct the query

Yahoo offers a REST interface to handle the conversion so we can use either a plain HTTP GET request, or if you want to do it inside of a script that is doing many other things you can use CURL, a set of very useful functions for querying and "scraping" web pages and applications.

We must construct the url according to the api guidelines, which boils down to something like this:

	$url =  "http://local.yahooapis.com/MapsService/V1/geocode";
	$args = "?appid=your_key_";
	$args .= "&street=" . urlencode(street_address);  //We must urlencode variables that will have spaces/etc
	$args .= "&city=" . urlencode(city);
	$args .= "&state=" . state;
	$args .= "&output=php";  //Optional parameter to return a php object
	$url = $url . $args;

The code above basically asks yahoo to use the current key to return the latitude and longitude as a serialized php object (the other option is xml, but I don't like parsing it).

Step 3 - Send the query

Sending the query via CURL works something like this:

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_TIMEOUT, 5000);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$address_data = unserialize(curl_exec($ch));
	curl_close($ch);

The script is doing the following:

  1. Initializing a CURL object.
  2. Setting the timeout to 5 seconds.
  3. Setting the url to query.
  4. Setting CURL to return the results to a variable rather than displaying it to the screen.
  5. Reading the results, unserializing them, and storing the results in our $address_data object, which is really just a bunch of nested arrays.

Step 4 - Get the latitude and longitude

You can retrieve the latitude and longitude this way:

	$latitude = $address_data['ResultSet']['Result']['Latitude'];
	$longitude = $address_data['ResultSet']['Result']['Longitude'];

That's all there is to it.

About the author

Jeremy Tunnell
I study meditation and write some software.

Comments

Get in touch

You can reach Jeremy at [email protected]