Archive for April, 2008

Published by Shawn on 13 Apr 2008

Google Maps API; A Tutorial

Step 1: Google Maps API Key

Note: this didn’t come out as expected during the Wordpress migration :(

In order to get a map on your site you must first sign up for a Google Maps API Key. There is no charge for this. Just make sure you follow the Google Maps Terms and Conditions.

The official Google Maps Documentation contains specifc API commands for more advanced users.

The “Hello World” of Google Maps
For the most part, basic Google Maps are fairly trivial. It’s when you’re handling 2 million data points is when it gets a bit tricky.

See Example
*note: I like to stick with the latest web standards, hence the strict DOCTYPE*

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/2001/REC-xhtml11-20010531/DTD/xhtml11-flat.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<meta http-equiv=”Content-Type” content=”text/javascript;
charset=iso-8859-1″ />
<meta name=”description” content=”Google Maps Basic Example” />
<meta name=”keywords” content=”" />
<title>My First Google Map</title>
<script
src=”http://maps.google.com/maps?file=api&v=2.44&key=your_map_key”
type=”text/javascript”></script>
<script type=”text/javascript”>
//<![CDATA[

// this is the javascript that is responsible for generating the map
function load_map() {
if (GBrowserIsCompatible()) {

// assign an id to the location in the html,
// in this case it is a div element
var map = new GMap2(document.getElementById("map"));

// latitude and longitude of center of map, on load
// the 18 is for the zoom level
map.setCenter(new GLatLng(41.902277, -87.62832), 18);
}
}

//]]>

</script>
</head>

<body onload=”load_map()” onunload=”GUnload()”>

<div id=”map” style=”width: 500px; height: 300px”></div>
<br/>
</body>
</html>

Google Map Controls

In order to zoom or pan or view different versions of the map (Satellite or Hybrid) you need to add some more JavaScript.

This adds basic zoom and pan controls to your map (See Example)

function load_map() {
if (GBrowserIsCompatible()) {

// assign an id to the location in the html,
// in this case it is a div element
var map = new GMap2(document.getElementById(”map”));

map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());

// latitude and longitude of center of map, on load
// the 18 is for the zoom level
map.setCenter(new GLatLng(41.902277, -87.62832), 8);
}
}

Add a Marker and Info Window

Generally speaking, data points can be sent in XML format and loaded onto the map. This is just the basic way to include a data point (marker) and it’s corresponding Info Window.

// Adds a marker at the given point with an info window
function createMarker(point, data) {
var marker = new GMarker(point);
GEvent.addListener(marker, “click”, function() {
marker.openInfoWindowHtml(data);
});
return marker;
}

function load_map() {
if (GBrowserIsCompatible()) {

// assign an id to the location in the html,
// in this case it is a div element
var map = new GMap2(document.getElementById(”map”));

// this will add a larger zoom control to the map
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());

// latitude and longitude of center of map, on load
// the 8 is for the zoom level
map.setCenter(new GLatLng(41.902277, -87.62832), 8);

// Add a marker with an Info Window
var point = new GLatLng(41.91862,-87.86590);

// you can also style the info window
var html = ‘<div style=”color:#005;width:200px;”>’;
html += ‘Check out our other maps at ‘;
html += ‘<a href=”http://www.fishing-locations.com”‘;
html += ‘title=”Fishing Locations and Google Maps”>’;
html += ‘fishing-locations.com</a></div>’;
var marker = createMarker(point,html);

// add the marker to the map
map.addOverlay(marker);
}
}

This adds a marker and corresponding info window. (See Example)

AJAX Your Google Map

One of the cool features of Google Maps API is that it allows you to grab the data using Asynchronous Javascript and XML, better known as AJAX.

This allows you to update the map without refreshing the page. This example gives a basic outline of the request and response activity when the user loads the page.

This adds a marker and corresponding info window. (See Example)

function load_map() {
var map = new GMap2(document.getElementById(”map”));
// this will add a larger zoom control to the map
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());

// latitude and longitude of center of map, on load
// the 8 is for the zoom level
map.setCenter(new GLatLng(41.902277, -87.62832), 4);

// Read the data from example.xml
var request = GXmlHttp.create();
request.open(”GET”, “data.xml”, true);

// this is how the ajax is performed
// this part of the script sends a request to the server
// and receives the data.xml file
request.onreadystatechange = function() {
if (request.readyState == 4) { // when all is clear
var xmlDoc = request.responseXML;

// get the marker array and parse the data
var markers = xmlDoc.documentElement.getElementsByTagName(”marker”);

// for each marker, get the attributes and the infowindow data
for (var i = 0; i < markers.length; i++) {
// parse the marker attributes
var lat = parseFloat(markers[i].getAttribute(”lat”)); // lat
var lng = parseFloat(markers[i].getAttribute(”lng”)); // long
var point = new GLatLng(lat,lng); // create the point
// get the infowindow data
var html = GXml.value(markers[i].getElementsByTagName(”infowindow”)[0]);
// create the marker
var marker = createMarker(point,html);
// add the marker to the map
map.addOverlay(marker);
}
}
}
// this sends the ajax request
request.send(null);

} // end load_map()

Here are some of my favorite resources for building Google Maps.

Check out a few of the Google Maps Extended APIs

Published by Shawn on 13 Apr 2008

PHP MySQL Connection Class

This PHP helper class allows you to easily connect to your MySQL database.

There are a couple other functions that may prove useful such as:
mysql_result_all() - Displays results in a table

getUserIP() - returns the User’s IP address
validate_email() - returns boolean if email validates.

You must change the database information to your particular database.

<?php

/**

* DB_Connect.php

* @author Shawn McFarlane

* @version $Id$

* @copyright 2005

**/

class DB_Connect{

// change these values

var $host “”;

var 

$user “”;

var 

$pass “”;

var 

$db “”;

function 

query_db($query)

{

    

$conn mysql_connect($this->host$this->user$this->pass);

    if (!

$conn) {

        die(

‘Could not connectooo: ’ mysql_error());

    }

    

mysql_select_db($db);

    

$results mysql_query($query$conn);

    

mysql_close($conn);

    return 

$results;

}

function 

mysql_insert($query)

{

    

$results $this->query_db($query);

    return 

$results;

}

/*

 * Displays results in table format

 *

*/

function mysql_result_all($resultz$rownumber)

{

    echo 

‘<table align=”center” class=”atablelayout1″ cellspacing=”2″>’;

    for(

$i 0$i mysql_num_fields($resultz); $i++) {

        echo 

‘<th class=”aheader”>’;

        echo 

mysql_field_name($resultz$i);

        echo 

‘</th>’;

    }

    

$rowCounter 1;

    while (

$row mysql_fetch_array($resultz)) {

        echo 

‘<tr>’;

        for(

$i 0$i $rownumber$i++) {

            echo 

‘<td class=”arow’ $rowCounter ‘”>’ $row[$i] . ‘</td>’;

        }

        echo 

‘</tr>’;

        if (

$rowCounter === 1) {

            

$rowCounter 2;

        } else {

            

$rowCounter 1;

        }

    }

    echo 

‘</table>’;

    include(

‘./includes/bottom.inc’);

}

/*

 * returns the User IP Address

 *

 *

*/

function getUserIP()

{

   

$ip “”;

   if (isset(

$_SERVER)){

       if (isset(

$_SERVER["HTTP_X_FORWARDED_FOR"])){

           

$ip $_SERVER["HTTP_X_FORWARDED_FOR"];

       } elseif (isset(

$_SERVER["HTTP_CLIENT_IP"])) {

           

$ip $_SERVER["HTTP_CLIENT_IP"];

       } else {

           

$ip $_SERVER["REMOTE_ADDR"];

       }

   } else {

       if ( 

getenv‘HTTP_X_FORWARDED_FOR’ ) ) {

           

$ip getenv‘HTTP_X_FORWARDED_FOR’ );

       } elseif ( 

getenv‘HTTP_CLIENT_IP’ ) ) {

           

$ip getenv‘HTTP_CLIENT_IP’ );

       } else {

           

$ip getenv‘REMOTE_ADDR’ );

       }

   }

   return 

$ip;

}

/*

 *

 *

 *

*/

function authenticate($field)

{

    

// To foil any possible attempts at SQL injection,

    // do the following function

    // $variable=str_replace(”what to look for”,

    //           ”what to replace it with”,$what_variable_to_use);

    // Now use the replace function on our variables

    

if(trim($field) == “” || $field == null) return false;

    

$field str_replace(“ ”“”$field); //remove spaces from password

    

$field str_replace(“%20″“”$field); //remove escaped spaces from password

    // And finally, add slashes to escape things like quotes and apostrophes

    // because they can be used to hijack SQL statements!

    // use the function, addslashes(), pretty self explanatory

    //$field = addslashes($field); //remove spaces from password

    

return $field;

// end authenticate()

function validate_email($email)

{

   

// Create the syntactical validation regular expression

   

$regexp =

    

“^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$”;

   

// Presume that the email is invalid

   

$valid 0;

   

// Validate the syntax

   

if (eregi($regexp$email))

   {

      list(

$username,$domaintld) = split(“@”,$email);

      

$valid 1;

   } else {

      

$valid 0;

   }

   return 

$valid;

}

}

?>

« Prev - Next »