PJ Hile

Don’t worry, I’m from the Internet.

PJ Hile header image 2

Putting a Google Map on your site with PHP: Part 1

March 24th, 2008 · 1 Comment

Google MapThe first step in getting a Google map on your site is to get the latitude and longitude coordinates of all the points you want to show. I get my coordinates using geocoding in the Google Maps API. In order to use the Google Maps API, you must sign up for a free key here.

Once you have your key, it’s as simple as:

// Desired address
$address = "http://maps.google.com/maps/geo?q="
.urlencode($data['address'])
.”,+”.urlencode($data['city'])
.”,+”.urlencode($data['state'])
.”,+”.urlencode($data['zip'])
.”&output=xml&key=”.$_SESSION['GOOGLE_KEY'];


// Retrieve the URL contents
$page = file_get_contents($address);


// Parse the returned XML file
$xml = new SimpleXMLElement($page);


// Parse the coordinate string
list($longitude, $latitude, $altitude) = explode(",", $xml->Response->Placemark->Point->coordinates);

We now have $longitude/$latitude, which we will need for rendering our map.

Notes:

  • I used to get the coordinates inside of my map generation, but sometimes the map would finish rendering before all the coordinates had been downloaded, so I suggest you get all your coordinates before you render your map.
  • My example makes use of SimpleXMLElement() which I believe is a PHP5 and above only function. If you use PHP4 or below, you will have to parse the xml some other way.
  • You don’t need the altitude for map generation, but they give it to us anyway.

Tags: Google · PHP

1 response so far ↓

  • 1 Clops // Apr 14, 2008 at 7:48 pm

    Just a note for people needing addresses from non-english speasking countries — the google maps geocoder will return the XML in ISO, thus the need to run the XML through iconv before passing it to simple XML

Leave a Comment