Google Maps API part 2: Retrieving Postcodes from your database

Google Maps API part 2: Retrieving Postcodes from your database

OK, this is a simple way to get your postcode/ address location returned and displayed via the Google Maps API on your own website. I’ll cover the ‘nearest store locator’ scenario in another post where you want places with a certain radius of an inputted postcode/ town returned.

First of all we need to retrieve our results which should already be stored with a geocoded result using the previous tutorial here. remember that in order for this to work you need an API key from google – again check the previous tutorial for more info on this.

We’re going to need to pass the geocoded values retrieved from the database into javascript and there are a few ways of doing this. This is really the hardest part and the only work you really need to do to display your result on a map as the Google maps API does the rest of the work for you. So we can either do this via something like an AJAX request whereby you build your returned data into an XML file and then use javascript to read that. Or you can write your php inline inside the javascript, which is messy for multiple results but in the singular it should be fine.

First lets start with the chunk of javascript on the page that will display our map etc… This method just calls up a map from the API and then zooms, centers and adds a marker to a specified co-ordinate. This singular display is useful if you want to, for instance, display the location of a result in a popup/ overlay.

// your API key here.
<script src="http://maps.google.com/maps?file=api&v=2&key=" type="text/javascript"></script>
 
<script type="text/javascript">
// declare variable to store map
var map;
// declare variable to store co-ordinates - fetch these from your database
var coords = new GLatLng(51, -1);
// details variable to store your address etc.. from your database
var details = "Your address details here...";
 
// function to load API map with marker and zoomed to location
function loadMap() {
	if (GBrowserIsCompatible()) {
		// load the map into the HTML element
        map = new GMap2(document.getElementById('map'));
        // add the map controls
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        // set the boundaries to the location
        var bounds = new GLatLngBounds();
        bounds.extend(coords);
        // center the map around the pointer
        map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
        // add the marker to the map
		var marker = new GMarker(coords);
		map.addOverlay(marker);
		// show the details/ popup window
		marker.openInfoWindowHtml(details);
	}
}
</script>

To see the map just add in a HTML element and set an onload event assigned to your body tag as thus

<body onload="loadMap()" onunload="GUnload()" >
  <div id="map" style="overflow: hidden; width:400px; height:400px"></div>
</body>

So now we just need to pass in our result from the database. Starting with passing it inline to javascript variable we can do the following, first connect and get your results from your database, very basically as below.

<?php
 
// connect to your database
 
// retrieve the results
$result = mysql_query("SELECT * FROM <table name> LIMIT 1");
 
// assign the results to variables something like:
while ($row = @mysql_fetch_assoc($result)){
$lat = $row['lat'];
$lng = $row['lng'];
}
?>

Ok, so in javascript we can then put in our php values:

 
// declare variable to store co-ordinates - fetch these from your database
<?php echo "var coords = new GLatLng($lat, $lng)\;";?>
// var coords = new GLatLng(51, -1);
// or you can do this:
// var coords = new GLatLng(<?php=$lat;?>, <?php=$lng;?>);

So all together the php page will look something like this:

<?php
 
// connect to your database
 
// retrieve the results
$result = mysql_query("SELECT * FROM <table name> LIMIT 1");
 
// assign the results to variables something like:
while ($row = @mysql_fetch_assoc($result)){
$lat = $row['lat'];
$lng = $row['lng'];
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
 
    <script src="http://maps.google.com/maps?file=api&v=2&key=" type="text/javascript"></script>
 
    <script type="text/javascript">
 
// declare variable to store map
var map;
// declare variable to store co-ordinates - fetch these from your database
<?php echo "var coords = new GLatLng($lat, $lng)\;";?>
// details variable to store your address etc.. from your database
var details = "Your address details here...";
 
// function to load API map with marker and zoomed to location
function loadMap() {
	if (GBrowserIsCompatible()) {
		// load the map into the HTML element
        map = new GMap2(document.getElementById('map'));
        // add the map controls
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        // set the boundaries to the location
        var bounds = new GLatLngBounds();
        bounds.extend(coords);
        // center the map around the pointer
        map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
        // add the marker to the map
		var marker = new GMarker(coords);
		map.addOverlay(marker);
		// show the details/ popup window
		marker.openInfoWindowHtml(details);
	}
}
 
 
 
 
  </script>
 
 
  </head>
 
<body onload="loadMap()" onunload="GUnload()" >
  <div id="map" style="overflow: hidden; width:400px; height:400px"></div>
</body>
</html>

For retrieving the results via an XML file instead I’ll cover that in part 3 as its much more applicable there.

This content is published under the Attribution-Noncommercial-Share Alike 3.0 Unported license.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • StumbleUpon
  • Reddit
  • TwitThis
  • Facebook
  • Google Bookmarks
  • MySpace
  • Technorati
  1. Google Maps API part 1: Accurate Geocoding for UK Postcodes
  2. Using Javascript/ AJAX to post HTML form data
  3. Creating XML from PHP/ MySQL for use with SPRY
  4. Quick popup/overlay show and hide a layer with Javascript and CSS
  5. Using SPRY to fetch values from a URL
  6. Upload a File Using PHP
  7. Joining columns/ concatenate strings in Oracle PLSQL/ MySQL