PHP Geocoding function, from address to coordinates lat long

This is a small function included in the Minibots Class that converts an address to a couple of coordinates Latitude,…

January 24, 2011

This is a small function included in the Minibots Class that converts an address to a couple of coordinates Latitude, Longitude that can be used to place a marker on a map.
This function uses Google’s geocoding service called with the file_get_contents function (CURL not needed).
The result is decoded with a preg_match call that searches for the center data of the map returned.
You can test the function with this online demo.

// ------------------------------------------
// converts a string with a stret address
// into a couple of lat, long coordinates.
// ------------------------------------------
public function getLatLong($address){
	if (!is_string($address))die("All Addresses must be passed as a string");
	$_url = sprintf('http://maps.google.com/maps?output=js&q=%s',rawurlencode($address));
	$_result = false;
	if($_result = file_get_contents($_url)) {
		if(strpos($_result,'errortips') > 1 || strpos($_result,'Did you mean:') !== false) return false;
		preg_match('!center:\s*{lat:\s*(-?\d+\.\d+),lng:\s*(-?\d+\.\d+)}!U', $_result, $_match);
		$_coords['lat'] = $_match[1];
		$_coords['long'] = $_match[2];
	}
	return $_coords;
}

Author

I'm a software engineer, an everyday web developer and a maker. I usually build sites with PHP, within or without WordPress. I build Internet of Things with Arduino and ESP8266. I'm the founder of Rockit.it and Dailybest.it and I'm actually the Chief Technical Officer of Better Days web agency.

Comments on “PHP Geocoding function, from address to coordinates lat long”

15 thoughts

  1. Eric says:

    Pardon my ignorance, but would you please explain in laymen terms exactly how to implement this. Thanks!

  2. Paweł P. says:

    Oooo yes! U just saved me a few hours of work! Good job!
    Best regards! Paweł

  3. test says:

    Not Working At All ..

  4. Giorgio says:

    Really Thanks!

    i needed it!

    Thaaanks

  5. Ryan says:

    A better solution would be to use json_decode on the data. Running some benchmarks between the two on average json_decode is faster than preg_match.

    // ——————————————
    // converts a string with a stret address
    // into a couple of lat, long coordinates.
    // ——————————————
    public function getLatLong($address){
    if (!is_string($address))die(“All Addresses must be passed as a string”);
    $_url = sprintf(‘http://maps.google.com/maps?output=js&q=%s’,rawurlencode($address));
    if($_result = file_get_contents($_url)) {
    $_result = json_decode($_result);
    if($_result !== false || !empty($_result->results)) {
    return $_result->results[0]->geometry->location;
    }
    }
    return false;
    }

  6. Zerovic says:

    awesome little snippet :) thanks a lot!

    Eric, the usage is pretty simple. add this into a php file, create a variable like
    $address = “Rome, Italy”;

    then simple use the function;)

    print_r(getLatLong($address));

    or

    $coordinates = getLatLong($address);

    $lat = $coordinates[‘lat’];
    $long = $coordinates[‘long’];

    hope it helps!

  7. Renga says:

    Big thanks for this sharing. Very helpfull for my works.

  8. Jay says:

    Thanks for this, had no idea this could be done in so few lines of code!

  9. peraferrer says:

    I needed to make a function that from a coordinate I’m back in that place and turned out something like this:

    // from a pair (lat, long) coordinates to an address, city, state, country
    function getCityFromLatLong($latLong){
    if (!is_string($latLong))die(“All Addresses must be passed as a string”);
    $_url = sprintf(‘http://maps.google.com/maps?output=js&q=%s’,rawurlencode($latLong));
    $_result = false;
    if($_result = file_get_contents($_url)) {
    if(strpos($_result,’errortips’) > 1 || strpos($_result,’Did you mean:’) !== false) return false;
    preg_match(‘/addressLines:\[.*?\]/’, $_result, $_match);
    $_explode = explode(‘,’, substr($_match[0], strpos($_match[0], ‘,’)+2, strrpos($_match[0], ‘”‘)-strpos($_match[0], ‘,’)-2));
    $_place[‘street’] = substr($_match[0], strpos($_match[0], ‘”‘)+1, strpos($_match[0], ‘,’)-strpos($_match[0], ‘”‘)-2);
    $_place[‘city’] = $_explode[0];
    $_place[‘state’] = $_explode[1];
    $_place[‘country’] = $_explode[2];
    }
    return $_place;
    }

    Surely you can improve, and I’m not exported in regular expreciones as you can see. Any recommendation is welcome.

  10. Thanks for this fine function, it helped me a lot.

  11. Stefano says:

    Yeah! Fantastic! Thanks man!

  12. Shiva says:

    Thanx for the code, was very helpful! :-)

  13. Luke HM says:

    Worked for me
    By far the simplest solution I have seen
    Many Many Thanks
    Luke

Comments are closed

Recommended

Scraping content with PHP as if it was jQuery

Building a spider or a bot needs some knowledge of regular expressions, you must know and use preg_match or preg_match_all…

December 8, 2013

Get instagram data without official api in PHP

Instagram has an official API to interact with its database of images and users. If you have enough time to…

December 3, 2013

Make a cron job with IFTTT

Cron is a software utility, a time-based job scheduler in Unix-like computer operating systems. People who set up and maintain…

November 12, 2013

How to read facebook likes count from PHP

When you add facebook like button to your site, probably, you also want to save the number of likes of…

October 8, 2012

PHP code to check if remote mp3 exists

Hi, I’ve a big table with thousands of mp3 links. Sice these links come from an old database, many of…

November 1, 2011

How to use Instagr.am photos on your site

UPDATE: 2013-12-04 I’ve made a method in the Mini Bots PHP Class that lets you retrieve images from instagram without…

August 18, 2011