Solved

How to use Google Maps API with PHP?

Posted on 2009-06-30
5
536 Views
Last Modified: 2013-12-13
How do I use Google Maps to display points on a map corresponding to several cities?
0
Comment
Question by:dilithiumtoys
  • 4
5 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 24748803
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
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 24748855
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
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 24748872
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
 

Author Closing Comment

by:dilithiumtoys
ID: 31598438
Thanks that jump started me!
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 24750628
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

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This tutorial walks through the best practices in adding a local business to Google Maps including how to properly search for duplicates, marker placement, and inputing business details. Login to your Google Account, then search for "Google Mapmaker…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now