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,…

Gennaio 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

PHP expert. Wordpress plugin and theme developer. Father, Maker, Arduino and ESP8266 enthusiast.

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

15 thoughts

  1. Eric ha detto:

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

  2. Paweł P. ha detto:

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

  3. test ha detto:

    Not Working At All ..

  4. Giorgio ha detto:

    Really Thanks!

    i needed it!

    Thaaanks

  5. Ryan ha detto:

    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 ha detto:

    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 ha detto:

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

  8. Jay ha detto:

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

  9. peraferrer ha detto:

    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. Martijn Wiedijk ha detto:

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

  11. Stefano ha detto:

    Yeah! Fantastic! Thanks man!

  12. Shiva ha detto:

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

  13. Luke HM ha detto:

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

Comments are closed

Recommended

Find values recursively inside complex json objects in PHP

A PHP function to to quickly search complex, nested php structures for specific values.

Dicembre 18, 2022

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…

Dicembre 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…

Dicembre 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…

Novembre 12, 2013

How many times a web link has been shared on Twitter

Twitter share button and Facebook share button are the most used buttons to share links on Internet. You can read…

Ottobre 19, 2012

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…

Ottobre 8, 2012