Dynamically using Iframe Maps with PHP GeoCoding and Google Maps API

Dynamically using Iframe Maps with PHP GeoCoding and Google Maps API

Dynamically using Iframe Maps with PHP GeoCoding and Google Maps API

In a recent project, EnlightenMental Productions needed to dynamically display a Google Map Iframe code based on the user’s current selection.  Each time an address was chosen, the <iframe> map would update to display the current address selected.

In order to do this, we needed to query the Google Maps API to get the longitude and latitude based on an address (1234 Somewhere Street City State Zipcode).  Using an article we found online (www.timshowers.com) and making a few minor adjustments, we created a basic PHP script that will generate a dynamic <iframe>.

<?php // First, setup the variables you will use on your
// Your Iframe will need a Width and Height set
// as well as the address you plan to Iframe
// Don't forget to get a Google Maps API key

$latitude = '';
$longitude = '';
$iframe_width = '400px';
$iframe_height = '400px';
$address = urlencode($address);
$url = "http://maps.google.com/maps/geo?q=".$address."&output=json&key=".$key;
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]); // Comment out the line below if you receive an error on certain hosts that have security restrictions
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$data = curl_exec($ch);
$geo_json = json_decode($data, true);

// Uncomment the line below to see the full output from the API request
// var_dump($geo_json);

// If the Json request was successful (status 200) proceed
if ($geo_json['Status']['code'] == '200') {

$latitude = $geo_json['Placemark'][0]['Point']['coordinates'][0];
$longitude = $geo_json['Placemark'][0]['Point']['coordinates'][1]; ?>

<iframe width="<?php echo $iframe_width; ?>" height="<?php echo $iframe_height; ?>" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="


&q=<?php echo $address; ?>
&hnear=<?php echo $address; ?>
&ll=<?php echo $longitude; ?>,<?php echo $latitude; ?>
&output=embed"> </ iframe >


} else { echo "<p>No Address Available</p>";}


The above code will output an Iframe into your site and use the dynamic address you’ve selected.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s