How to use Google Maps API with PHP?

How do I use Google Maps to display points on a map corresponding to several cities?
dilithiumtoysAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
You are into an area that has a LOT of documentation on the Google site, and it would be hard for me to add meaningfully to what they have written there.

The general process is like this.  You geocode the points you want to display.  You can use the Simple Geocoder class to get the lat/lon pair. Then you feed the lat/lon pairs to the Google Maps API.  The man page for the static maps is here:
http://code.google.com/apis/maps/documentation/staticmaps/

More to follow...
<?php // RAY_geocoder.php
 
// API KEYS, ETC.
require_once('_config.php');
 
// A FREEFORM LOCATION STATEMENT IS OPTIONAL (BUT NOT USED HERE)
$location = '';
if (!empty($_GET)) {
	foreach ($_GET as $k => $v) { $$k = get_clean_text_string($v); }
	if ($a != '') { $location .= $a . ' '; }
	if ($c != '') { $location .= $c . ' '; }
	if ($s != '') { $location .= $s . ' '; }
	if ($z != '') { $location .= $z . ' '; }
	$location = trim($location);
}
 
?>
<html><head><title><?=$a?> <?=$c?> <?=$s?> <?=$z?> Yahoo/Google Geocoder Query</title></head>
<body>
<form method="get">
Addr: <input type="text" name="a" autocomplete="off" value="<?=$a?>" />
City: <input type="text" name="c" autocomplete="off" value="<?=$c?>" />
ST:   <input type="text" name="s" autocomplete="off" value="<?=$s?>" size="2" />
Zip:  <input type="text" name="z" autocomplete="off" value="<?=$z?>" size="8" />
<input type="submit" name="_go" value="go" />
</form>
</body>
</html>
<?php
 
if (empty($_GET)) { die(); }
 
 
error_reporting(E_ALL);
 
 
// PREPARE THE GEOCODER
$y_demo			= new SimpleGeoCoder;
$y_demo->address	= $a;
$y_demo->city		= $c;
$y_demo->state		= $s;
$y_demo->zip		= $z;
 
// TEST THE YAHOO! GEOCODER
$y_demo->YahooGeoCode();
echo "<pre>\n\nYAHOO! ";
print_r($y_demo);
echo "</pre>\n";
 
 
// PREPARE THE GEOCODER
$g_demo			= new SimpleGeoCoder;
$g_demo->address	= $a;
$g_demo->city		= $c;
$g_demo->state		= $s;
$g_demo->zip		= $z;
 
 
// TEST THE GOOGLE GEOCODER
$g_demo->GoogleGeoCode();
echo "<pre>\n\nGOOGLE ";
print_r($g_demo);
echo "</pre>\n";
 
 
// ALL DONE
die();
 
 
 
// SIMPLE GEOCODER CLASS
class SimpleGeoCoder
{
 
// DECLARE THE INPUT DATA
public $location; // USE THIS FOR A FREEFORM QUERY, OR USE THESE PARTS
public $address;
public $city;
public $state;
public $zip;
 
// DECLARE THE WORKING DATA
private $precis; // TEXTUAL PRECISION FROM YAHOO
private $yfp, $yahoo_url,  $y_buf, $ydata;
private $gfp, $google_url, $g_buf, $gdata;
 
// DECLARE THE OUTPUT DATA
public $latitude;
public $longitude;
public $precision;
public $warning;
public $geocoder;
 
// DECLARE THE CONSTRUCTOR
public function __construct()
{
	$this->latitude		= 0.0;
	$this->longitude	= 0.0;
	$this->precision	= FALSE; // WANT A VALUE OF 5 OR HIGHER, HIGHER IS BETTER
	$this->warning		= '';
	$this->geocoder		= '';
}
 
 
// DECLARE THE YAHOO! VERSION OF THE WORKHORSE
public function YahooGeoCode()
{
	$this->geocoder	= 'Yahoo!';
	$yahoo_url	= "http://local.yahooapis.com/MapsService/V1/geocode?&appid=" . YAHOO_API;
 
	if ($this->location != '') // YOU CAN ASK FOR A FREEFORM QUERY
	{
		$yahoo_url	.= "&location=" . urlencode($this->location);
	}
	else // YOU CAN ASK FOR INDIVIDUAL PIECES OF AN ADDRESS
	{
		$yahoo_url	.= "&street=" . urlencode($this->address);
		$yahoo_url	.= "&city="   . urlencode($this->city);
		$yahoo_url	.= "&state="  . urlencode($this->state);
		$yahoo_url	.= "&zip="    . urlencode($this->zip);
	}
 
// EXECUTE YAHOO GEOCODER QUERY
// NOTE - USE ERROR SUPPRESSION OR IT WILL BARF UP THE YAHOO API - ON FAILURE RETURNS HTTP 400 BAD REQUEST
	if ($yfp = @fopen($yahoo_url, 'r'))
	{
		$y_buf	= '';
		while (!feof($yfp)) { $y_buf .= fgets($yfp); }
		fclose($yfp);
	}
	else
	{
		return FALSE;
	}
 
// EXAMINE THE RESULT
	if ($y_buf != '') // NOT EMPTY, WE GOT DATA
	{
		$ydata	= new SimpleXMLElement($y_buf);
 
// CHECK FOR ANY ERROR MESSAGE, IF NONE, EXTRACT THE DATA POINTS
		$y_err	= $ydata->Message;
		if ($y_err == '')
		{
			$this->precis		= $ydata->Result["precision"];
			$this->warning		= $ydata->Result["warning"];
			$this->latitude		= $ydata->Result->Latitude;
			$this->longitude	= $ydata->Result->Longitude;
			$this->address		= $ydata->Result->Address;
			$this->city		= $ydata->Result->City;
			$this->state		= $ydata->Result->State;
			$this->zip		= $ydata->Result->Zip;
 
// SET PRECISION TO A NUMBER VALUE
			if ($this->precis == 'zip')	{ $this->precision = "5"; }
			if ($this->precis == 'street')	{ $this->precision = "6"; }
			if ($this->precis == 'address')	{ $this->precision = "8"; }
		}
		else
		{
			return FALSE;
		}
	}
	else  // NO RESULT - SOMETHING IS SICK AT YAHOO
	{
		return FALSE;
	}
return TRUE;
} // END function YahooGeocode
 
 
// DECLARE THE GOOGLE VERSION OF THE WORKHORSE
public function GoogleGeoCode()
{
	$this->geocoder	= 'Google';
	$google_url	= "http://maps.google.com/maps/geo?key=" . GOOGLE_API . "&output=csv";
 
	if ($this->location != '') // YOU CAN ASK FOR A FREEFORM QUERY
	{
		$google_url	.= "&q=" . urlencode($this->location);
	}
	else // YOU CAN ASK FOR INDIVIDUAL PIECES OF AN ADDRESS
	{
		$google_url	.= "&q=" . urlencode(trim($this->address .' '. $this->city .' '. $this->state .' '. $this->zip));
	}
 
// EXECUTE GOOGLE GEOCODER QUERY
	if ($gfp = @fopen($google_url, 'r'))
	{
		$g_buf = '';
		while (!feof($gfp)) { $g_buf .= fgets($gfp); }
		fclose($gfp);
	}
	else
	{
		return FALSE;
	}
 
// EXTRACT THE DATA
	$gdata	= explode(',',$g_buf);
	if ($gdata[0] != '200') // RESPONSE CODE SHOULD BE '200' -- IF 602 - BAD ZIP CODE OR UNUSABLE ADDRESS
	{
		return FALSE;
	}
	$this->precision	= $gdata[1]; // GEOCODE ACCURACY - ZIP CODE = 5, HIGHER NUMBERS ARE BETTER
	$this->latitude		= $gdata[2];
	$this->longitude	= $gdata[3];
return TRUE;
} // END function GoogleGeocode
 
 
} // END class SimpleGeocoder

Open in new window

0
Ray PaseurCommented:
Next you create a map url that you will feed to client HTML in the image tag.  For each point you want to mark, you add another marker tag, consisting of a latitude, longitude and a color for the pointer.
// GOOGLE STATIC MAP SETUP - SEE 
// http://code.google.com/apis/maps/documentation/staticmaps/
 
// GOOGLE MAP VARIABLES
// $my_zoom	= '13'; // IF NO SPEC, THE VIEWPORT IS AUTOMATICALLY ADJUSTED
$my_size	= '600x396';
$my_form	= 'png8';
$my_type	= 'roadmap';
 
// GOOGLE MAP URL
$mapurl		= "";
$mapurl		.= "http://maps.google.com/staticmap?sensor=false&key=" . GOOGLE_API;
$mapurl		.= "&center=$my_lat,$my_lon";
$mapurl		.= "&zoom=$my_zoom&size=$my_size";
$mapurl		.= "&format=$my_form";
$mapurl		.= "&type=$my_type";
 
// ADDING MARKER DESCRIPTORS AT THE END OF THE URL
$mapurl		.= "&markers=";
 
// SETTING UP MARKER DESCRIPTORS
$marker		= "$my_lat,$my_lon,white|"; // DEFAULT IS ME AT CENTER

Open in new window

0
Ray PaseurCommented:
Then you echo out an image tag like this...

Hope that helps.  The whole thing has a lot of moving parts, so do not be surprised if it takes you a few days to get it all together.  Also, a little OT, but I have found that the maps sometimes hang if there is also a lot of Google advertising on the same page.  YMMV, but I put a note on the page above the map telling the client to refresh the page if the map does not appear.  Only a few complaints so far.

Best of luck with it, ~Ray
echo "<div id='map_canvas' class='GoogleMapLocator'>\n";
echo "<img src=\"$mapurl\" />\n";
echo "</div>\n";

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
dilithiumtoysAuthor Commented:
Thanks that jump started me!
0
Ray PaseurCommented:
Thanks for the points - it's a great question.  Be sure to check the Google Maps T/C carefully - if you are using a mobile device you must tell them about it.  Best regards, ~Ray
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.