We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

How to use Google Maps API with PHP?

dilithiumtoys
on
Medium Priority
668 Views
Last Modified: 2013-12-13
How do I use Google Maps to display points on a map corresponding to several cities?
Comment
Watch Question

Most Valuable Expert 2011
Author of the Year 2014

Commented:
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

Most Valuable Expert 2011
Author of the Year 2014

Commented:
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

Most Valuable Expert 2011
Author of the Year 2014
Commented:
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview

Author

Commented:
Thanks that jump started me!
Most Valuable Expert 2011
Author of the Year 2014

Commented:
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
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a free trial preview!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.