Showing polylines on Google Maps Tutorial
This tutorial is (c) 2005 by Hans van der Maarel - Red Geographics. No parts of it can be reproduced without obtaining permission. Please be respectful.
This tutorial describes the way the Polylines sample on this website has been created. It uses version 2 of the Google Maps API. Any parts that differ significantly from version 1 will be indicated in bold. A version 1 sample of the same code is also available. Prerequisites
We are going to use PHP to dynamically create an HTML document with the appropriate Google Maps javascript code. At some points, indicated in [red], you will need to add your own specific details (Google Maps key, database connection details, etc.), omitting the [ and ]. |
![]() |
Database structure
The database can be recreated with this snippet of sql:
CREATE TABLE track (
id int(11) NOT NULL default '0',
geometry text NOT NULL )
TYPE=MyISAM;
The id field is actually not used at all. Also note that there are no additional fields to hold information like color. For this sample I am purely focussing on the geometry aspects.
Section 1: loading the data
I'm supplying the data initially in a CSV file (comma separated value), which can be downloaded here. In order to load this into the database I've written a custom database loader.
<?php
include_once('track_conf.php');
$lines = file('Track.csv');
$numlines = sizeof($lines);
$link = mysql_connect($dbserver, $username, $password)
or die("Could not connect: " . mysql_error());
mysql_selectdb($dbname,$link) or die ("Can\'t use " . $dbname . " : " . mysql_error());
for ($i = 0; $i <= ($numlines - 1); $i++) {
$values = explode("#", $lines[$i]);
$numcolumns = sizeof($values);
$sql = "INSERT INTO track VALUES ('";
$sql = $sql . $values[0] . "','";
$sql = $sql . $values[1] . "')";
$result = mysql_query($sql, $link);
if (!$result)
{
echo "<p>Due to an error (" . mysql_error() .
")<br>, your entry could not be loaded into the database. Row:" . $i;
} else {
echo "<p>Your entry has been loaded into the database.";
}
}
?>
This php script includes a file called track_conf.php, its purpose will be discussed later on. Simply upload this file along with the csv file to the website and running this from a browser will load the data into the database. It's a bit crude, but functional.
Section 2: track_conf.php
Over the course of working with Google Maps I have become a great fan of adding configuration stuff (i.e. a Google Maps key, the size of the map, initial zoom and location) in a separate configuration file, in this case track_conf.php. This makes it easier to change those aspects of the map, without having to dig through many lines of code. My track_conf.php looks like this:
<?php $dbserver = "[database server]";
$password = "[password]";
$username = "[username]";
$dbname = "[database name]"; $map_width = 600; $map_height = 700; $google_maps_key = "[your Google Maps key]";
$initial_lat = 36.9;
$initial_lon = -121.95;
$initial_zoom = 8; // 1 through 17
?>
The functions of these variables is pretty obvious. The initial zoom is limited in its options. Note that the zoom in the version 2 API works the other way around, a higher zoom-factor means more detail.
Section 3: header
<?php
include_once('track_conf.php');
?>
<html xmlns="http://www.w3.org/1999/xhtml"xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<title>Polylines read from MySQL database</title>
<link href="/style/hans.css" rel="stylesheet" type="text/css">
<script src="http://maps.google.com/maps?file=api&v=2&key=<?php echo $google_maps_key ?>" type="text/javascript"></script> <style type="text/css">
v\:*
{
behavior:url(#default#VML);
}
</style>
</head>
In here we can see one advantage of using a separate configuration file. Instead of listing my Google Maps code here, I simply refer to it in a bit of php code. The xmlns and style stuff that's in the header is necessary to make IE display the polylines. Note the v=2 in the script line that calls the Google Maps api.
Section 4: setting up the map
<body>
<div id="map" style="width: <?php echo $map_width ?>px; height: <?php echo $map_height ?>px"> </div> <script type="text/javascript">
//<![CDATA[ var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(<?php echo $initial_lat ?>, <?php echo $initial_lon ?>), <?php echo $initial_zoom ?>);
As you can see, the map is being defined, scale and type controls are added and an intial map view is set through the map.setCenter function. All the actual values for this are being read from the track_config.php. The map.setCenter function can also take a 4th parameter to specify the map type, but I've omitted it here so it will default to the normal map.
Section 5: reading information from the database
<?php
$link = mysql_connect($dbserver, $username, $password)
or die("Could not connect: " . mysql_error());
mysql_select_db($dbname,$link) or die ("Can\'t use database : " . mysql_error());
$sql = "SELECT * FROM track";
$result = mysql_query($sql,$link);
if (!$result)
{
//echo "no results";
}
while($row = mysql_fetch_array($result))
{
$geometry = str_replace("LINESTRING (","", $row['geometry']);
$geometry = str_replace(")","",$geometry);
$points = explode(",",$geometry);
$numpoints = sizeof($points);
echo "var polyline = new GPolyline([";
for ($i = 0; $i <= ($numpoints - 1); $i++) {
$coordinates = explode(" ",$points[$i]);
echo "new GLatLng(" . $coordinates[1] . "," . $coordinates[0] . ")";
if ($i != ($numpoints - 1)) {
echo ",\n";
} else {
echo "\n";
}
}
echo "],\"#ff0000\", 5, 1);\n";
echo "map.addOverlay(polyline);\n\n";
}
mysql_close($link);
?>
//]]>
</script>
</body>
</html>
The key difference here is the GLatLng function, which takes coordinates in the order lat, lon (as opposed to the old GPoint function in version 1, which took them as lon, lat).
This would be a good time to discuss how polylines are stored in OGC WKT , compared to Google:
| OGC WKT | |
| LINESTRING (-122.003 37.274,-121.999 37.272, -121.990 37.206) | new GPolyline([new GLatLng(37.4419,-122.1419), new GLatLng(37.4519,-122.1519)], "#ff0000", 10); |
The main difference is that a Google polyline is actually defined as an array of points whereas a OGC linestring is defined as a linear object, using up less storage space.
As you can see, the OGC geometry starts with LINESTRING ( and ends with a ). This is removed using the str_replace function. Then the explode function is used to turn the text string into an array. Because the coordinate pairs are separated by spaces in the OGC geometry, a space is used as 'explosion' character. Then for every element in the array (every point) this is repeated, using a comma as explosion character to separate the lat and lon. Again this is placed in an array.
Just like the other tutorials, I'm simply creating the javascript for Google to work with, nothing fancy here. One thing that is interesting to look at is the line echo "],\"#ff0000\", 5, 1);\n"; which occurs at the end of every polyline feature. This contains the color, in this case red (#ff0000), the line width (5) and the opacity (1, totally opaque).
And that's all there is to it. If you have any questions, or if this tutorial was of use to you, please feel free to let me know. Also, it would be much appreciated if you post a link to it on your Google Maps application.
In case you're wondering, the data comes from a road trip I took in October 2005, driving from San Jose to Monterey with a GPS receiver. I downloaded the track from the receiver and stored it as a GPX file. I then used FME by Safe Software to do some processing and created a text file with the geometry. I could have used FME to put the data directly into a MySQL database, but my ISP won't allow that. There are easier ways to display GPX data on Google Maps, I recently worked on one for Ferienregio Vinschgau.
This tutorial is (c) 2006 by Hans van der Maarel - Red Geographics. No parts of it can be reproduced without obtaining permission. Please be respectful.
Index : Google Maps API Overview : Tutorial - Polylines version 2