Google Maps API introduction tutorial using PHP and MySQL

advertisement
BTW@MDH
Google Maps API introduction tutorial using PHP
and MySQL
Version 1.0
BTW@MDH
Google Maps API introduction tutorial using PHP and MySQL
Version:
1.0
Date: 2008-11-09
Revision History
Date
2008-11-09
Doc. No.:
Version
0.01
Description
Initial Draft
Author
Mikael Forsgren
Internal-5
Page 2
BTW@MDH
Google Maps API introduction tutorial using PHP and MySQL
Version:
1.0
Date: 2008-11-09
1.Introduction
1.1Purpose of this document
The purpose of this document is to provide the user with a working example of a custom Google Map using a
database to load markers. This tutorial is very condensed and will not provide any in depth knowledge of either
PHP, SQL or Javascript. The reader is expected to have some knowledge of the previous mentioned languages.
1.2Document organization
The document is organized as follows:




Section 1, Introduction, gives a short overview of the tutorial's purpose.
Section 2, Gives a tutorial in how to create database tables, users and create custom maps
Section 3, Further reading
Section 4, Conclusion
1.3Intended Audience
The intended audience is:
 BTW@MDH project members
1.4Scope
This document will provide a simple example and get you started with PHP, MySQL and Google Maps API. It
is assumed that the reader has a working PHP, MySQL and Apache environment.
1.5Definitions and acronyms
1.5.1Definitions
Keyword
Definitions
1.5.2Acronyms and abbreviations
Acronym or
abbreviation
NTR
Definitions
Nothing to Report.
There is no information to a specific topic available or necessary.
1.6References
[1] http://code.google.com/support/bin/answer.py?answer=65622&topic=11364
[2] http://code.google.com/apis/maps/signup.html
Page 3
BTW@MDH
Google Maps API introduction tutorial using PHP and MySQL
Version:
1.0
Date: 2008-11-09
2. Tutorial overview
This tutorial is based on “Using PHP/MySQL with Google Maps” [1]. The code examples are taken from that
tutorial. The difference is that this tutorial will give you help creating SQL tables and give a very short overview
on how to create the custom map. The reader is encouraged to study the full tutorial for a deeper insight. This
document does not provide instructions how to secure your server. Therefor it's important that the reader makes
sure that the machine can't be accessed from a remote location.
2.1Creating Tables
We need to setup the database with a user and tables. To start we need to open the MySQL shell with the
command line client.
Start Menu\Programs\MySQL\MySQL Server 5.0\MySQL Command
Line Client
Enter the password to get access to the database. We want to create a database which we can use for our
example. Enter the following command into the shell to create the database “btw”.
create database btw;
We need to change our working database to btw with this command.
use btw;
In the next step we create a user called “pma” and we don't give this user a password. It's important that the
database and webserver you are using cannot be accessed from a remote location for security reasons.
create user 'pma'@'localhost';
This user need privileges to insert/select etc. The privileges are given by:
grant all privileges on btw.* to 'pma'@'localhost';
We are now ready to create tables and insert data into them. We will need the following files to load this data
into our database.
“createmarkerstable.sql”
CREATE TABLE `markers` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 60 ) NOT NULL ,
`address` VARCHAR( 80 ) NOT NULL ,
`lat` FLOAT( 10, 6 ) NOT NULL ,
`lng` FLOAT( 10, 6 ) NOT NULL ,
`type` VARCHAR( 30 ) NOT NULL
) ENGINE = MYISAM ;
“markers_data.sql”
INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('Pan Africa
Market', '1521 1st Ave, Seattle, WA', '47.608941', '-122.340145', 'restaurant');
INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('Buddha Thai
Bar', '2222 2nd Ave, Seattle, WA', '47.613591', '-122.344394', 'bar');
INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('The Melting
Pot', '14 Mercer St, Seattle, WA', '47.624562', '-122.356442', 'restaurant');
INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('Ipanema
Grill', '1225 1st Ave, Seattle, WA', '47.606366', '-122.337656', 'restaurant');
INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('Sake
House', '2230 1st Ave, Seattle, WA', '47.612825', '-122.34567', 'bar');
INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('Crab Pot',
'1301 Alaskan Way, Seattle, WA', '47.605961', '-122.34036', 'restaurant');
INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('Mama\'s
Mexican Kitchen', '2234 2nd Ave, Seattle, WA', '47.613975', '-122.345467', 'bar');
Page 4
BTW@MDH
Google Maps API introduction tutorial using PHP and MySQL
Version:
1.0
Date: 2008-11-09
INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('Wingdome',
'1416 E Olive Way, Seattle, WA', '47.617215', '-122.326584', 'bar');
INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('Piroshky
Piroshky', '1908 Pike pl, Seattle, WA', '47.610127', '-122.342838', 'restaurant');
We will load these files with the following commands:
source c:\[insert path here”\createmarkerstable.sql
source c:\[insert path here”\markers_data.sql
We are now done and can continue with the next step.
2.2Testing database connections
Before we can continue we must test if we can connect to the database. The following sourcecode files should
be placed in your Apache's htdocs directory.
“phpsqlajax_dbinfo.php” - This file contains username, password and the databasename. It's wise to separate
this information from other php files.
<?php
$username="pma";
$password="";
$database="btw";
?>
“sqltest.php” - This file will help you test and troubleshoot your database connection
<?php
require("phpsqlajax_dbinfo.php");
// Connect to the database
$dbhost = 'localhost';
$connection = mysql_connect("$dbhost","$username","$password");
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}
$db = mysql_select_db("$database", $connection);
if (!$db)
{
die('Couldn\'t select database.'. mysql_error());
}
// Tell User we are done.
echo 'Connection and database select complete successfully';
?>
To test the connection type the following into your web browser:
http://localhost/sqltest.php
If everything is fine can we continue to the next section
2.3 Generating XML
Google does not recommend the user to use the results from a SQL query and a build a custom map. The user is
encouraged to first generate XML and then load markers etc from this XML file. This approach is less
problematic and allows for a faster initial page load, a more flexible map application, and easier debugging. The
following code will generate XML output which will be easy to debug. By just running the file we will be told if
the XML is well formed.
Page 5
BTW@MDH
Google Maps API introduction tutorial using PHP and MySQL
Version:
1.0
Date: 2008-11-09
“xmltester.php” - Builds a XML DOM
<?php
require("phpsqlajax_dbinfo.php");
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) { die('Not connected : ' . mysql_error());}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name",$row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("type", $row['type']);
}
echo $dom->saveXML();
?>
2.4 Load generated XML data
From now on we will use JavaScript to build the map. We will use the function GdownloadURL to grab the
XML data. The first parameter will be our PHP script and the second parameter will be our callback function.
This callback function will iterate through the XML nodes. For each marker element found will we retrieve the
name, address, type, and lat/lng attributes and pass them to createMarker, which returns a marker that you can
add to the map.
“GdownloadURL”
GDownloadUrl("xmltester.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
Page 6
BTW@MDH
Google Maps API introduction tutorial using PHP and MySQL
Version:
1.0
Date: 2008-11-09
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, name, address, type);
map.addOverlay(marker);
}
});
“createMarker”
function createMarker(point, name, address, type) {
var marker = new GMarker(point, customIcons[type]);
var html = "<b>" + name + "</b> <br/>" + address;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
2.5 Testing the complete code
We are now ready to complete the JavaScript and embed it in a HTML file. Before we do that we need a
personal Google Maps API key [2]. Without this key it will not be possible to use the API. At the signup page
enter this in the domain box:
http://localhost
The complete HTML sourcecode:
“phpsqlajax_map.htm”
<!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"/>
<title>Google Maps AJAX + MySQL/PHP Example</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=INSERT API KEY HERE"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
//Defines custom icons
var iconBlue = new GIcon();
iconBlue.image = 'mm_20_blue.png';
iconBlue.shadow = 'mm_20_shadow.png';
iconBlue.iconSize = new GSize(12, 20);
iconBlue.shadowSize = new GSize(22, 20);
iconBlue.iconAnchor = new GPoint(6, 20);
iconBlue.infoWindowAnchor = new GPoint(5, 1);
var iconRed = new GIcon();
iconRed.image = 'mm_20_red.png';
iconRed.shadow = 'mm_20_shadow.png';
iconRed.iconSize = new GSize(12, 20);
iconRed.shadowSize = new GSize(22, 20);
iconRed.iconAnchor = new GPoint(6, 20);
iconRed.infoWindowAnchor = new GPoint(5, 1);
var customIcons = [];
customIcons["restaurant"] = iconBlue;
customIcons["bar"] = iconRed;
//This function is executed when the body is loaded
function load() {
Page 7
BTW@MDH
Google Maps API introduction tutorial using PHP and MySQL
Version:
1.0
Date: 2008-11-09
//check if the browser is compatible
if (GBrowserIsCompatible()) {
//create map and center it
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(47.614495, -122.341861), 13);
//Load the xml data from our xmltester.php file
GDownloadUrl("xmltester.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, name, address, type);
map.addOverlay(marker);
}
});
}
}
//create marker fucntion
function createMarker(point, name, address, type) {
var marker = new GMarker(point, customIcons[type]);
var html = "<b>" + name + "</b> <br/>" + address;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
//]]>
</script>
</head>
<body onload="load()" onunload="GUnload()">
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>
3. Further reading
These tutorials deals with PHP and MySQL
Using PHP and MySQL to create KML
http://code.google.com/support/bin/answer.py?answer=69906&topic=11367
Creating a Store Locator with PHP, MySQL & Google Maps
http://code.google.com/support/bin/answer.py?answer=87134&topic=11367&ctx=sibling
4.Conclusion
This tutorial should have given you a brief introduction to create a custom map using PHP, MySQL and
JavaScript.
Page 8
Download