GMap 2.3 Manual

Code322

Overview

GMap provides a PHP wrapper around the Google Maps Javascript API. Its purpose is to allow a web developer to easily add Google Maps and driving directions to web pages using PHP.

The GMap class is used to create and configure each map (and optional directions) on your page.

If you are creating a map without directions, you must add at least one GMarker object to the GMap. If you add more than one GMarker, the map will be automatically centered and zoomed to display all markers. The GMarker class is also used to set the marker info window contents. The GMap showLocation function will create a GMarker for you. This is useful if you only need one marker and do not need to customize it.

You can add GMarkers to a directions map. Markers will be displayed in addition to the start and end location markers. One or more markers may be added as waypoints to the directions.

The icon associated with each marker can be modified using the GIcon class. You can customize the icon for the entire map (all markers) or customize individual marker icons.

Geocoding is provided by the getLocation function and the GLocation class. These can be used to obtain the latitude and longuitude (as well as city, county, state, postal code, etc.) of any address that is recognized by Google.

System Requirements

Installation Instructions

  1. Configure

    Edit the gmap_config.php file:

    Set GOOGLE_MAP_API_KEY to the Google Map API key to you obtained from Google.

  2. Upload

    Upload everything to your site.
  3. Test Installation

    Open examples/index.php in a browser and view the examples.

Maps

Any page that contains a map must contain the following:

The div element

Specify the height and width of the map in pixels, either in the div tag itself or an external CSS file that is included in the head of the document. For example:

<div id="gmap" style="width:300px; height:300px"></div>

If you do not specify the width, the map will exand to fill its container.

NOTE: DO NOT use self-closing tags: />

If you have multiple maps on one page, each div id should be unique:

<div id="gmap1" style="width:300px; height:300px"></div>
<div id="gmap2" style="width:300px; height:300px"></div>
<div id="gmap3" style="width:300px; height:300px"></div>

PHP Code

You need PHP code to include the gmap.php file and create a GMap object.

A location string can be passed to the showLocation function. This will display the map centered on the location with a marker for the location.

<?php require_once('gmap.php');
$map = new GMap();
$map->showLocation('New York, NY');
?>

Alternately, an array of GMarker objects can be created and passed to the showMap function. This will display a map that is automatically zoomed and centered to include all locations/markers.

<?php require_once('../gmap.php');

$gmap = new GMap();

$markers[0] = new GMarker('New York, NY');
$markers[1] = new GMarker('Boston, MA');
$markers[2] = new GMarker('Washington, DC');

$gmap->showMap($markers);
?>

Marker Geocodes

In order for a marker to be displayed on a map, it's geocode (latitude/longitude) must be obtained. There is a daily limit on the number of geocode requests per day from any IP address. Exceeding this limit can result in having the IP address temporarily blocked. If the limits continue to be exceeded, the IP address may be blocked permanently.

There are three ways to obtain and set the marker's geocode:

  1. Browser Geocodes

    This is the default setting. The browser (client) obtains the geocode for a marker's address using Javacsript. Each request is counted against the browser's IP address.

  2. Server Geocodes

    You can have your server obtain the geocode for each address using PHP. Each request is counted againts the server's IP address.

    $gmap = new GMap();
    $gmap->server_geocodes = true;
    $gmap->showLocation('New York');

    NOTE: If your server obtains the geocodes, you run the risk of exceeding the daily limits and having your server's IP address blocked, either temporarily or permanently.

  3. Hardcoded

    If you already know a marker's lat/lon (i.e., from a database), you can specify them:

    $markers[0] = new GMarker('','Statue of Liberty');
    $markers[0]->lat = 40.689201355;
    $markers[0]->lon = -74.0447998047;

    This method avoids a geocode request in order to display the marker.

Driving Directions

Any page that contains Google driving directions must have the following elements:

In order for the polyline (the line from start location to end location) to show up in Internet Explorer, you must include the VML namespace in your page. Put this at the beginning of your page:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">

The div elements

One div element placeholder for the map and another for the driving directions.

<div id="gmap" style="width: 500px; height: 300px"></div>
<div id="dir" style="width: 500px; height: 800px"></div>

PHP Code

PHP code to include the gmap.php script and create a GMap object. The map and directions are displayed by calling the showDirections function with start and end address strings as arguments.

<?php require_once('gmap.php');
$gmap = new GMap();
$gmap->showDirections('Houston', 'Dallas');
?>

You can add one or more markers to the driving directions by creating an array of indexes. Each index corresponds to a marker in the GMap's marker array. For example:

$gmap->waypoints = array(0,1);

will add the first two markers as waypoints to the driving directions.

Locales

You can change the language of the directions by setting the locale. The following examples show how to set the locale for some selected languages:

French
$gmap->locale = 'fr';
German
$gmap->locale = 'de';
Greek
$gmap->locale = 'el';
Spanish
$gmap->locale = 'es';
Russian
$gmap->locale = 'ru';

Controls

Google Bar

A Google Bar is a control that allows a user to perform a search for locations within the map. To add a Google Bar to a map:

$gmap = new GMap(); 
$gmap->enable_google_bar = true; 

By default, a user must click on the Google Bar to expand it and display a field for search input. To show the Google Bar as already expanded when it is displayed:

$gmap = new GMap(); 
$gmap->enable_google_bar = true; 
$gmap->show_bar_on_load = true; 

Map Overview

A map overview is small corner map showing a wider area. To display a map overview:

$gmap = new GMap(); 
$gmap->show_overview_map_control = true; 

Overlays

AdSense

Fetch and display ads to the map by creating a GAdsManager object with your publisher ID.

$gmap->ads_manager = new GAdsManager('ca-pub-8909729629679521');

Traffic

You can display current road traffic information on your map for supported cities.

$gmap->traffic_overlay = true;

If you want a button to toggle the trafic overlay on/off, add the following to your page:

<input type="button" value="Toggle Traffic" onClick="toggleTraffic();"/>

For a checkbox:

<input type="checkbox" onClick="toggleTraffic();" checked="checked">Traffic

Polylines

To display a polyline on your map:

  1. Create an array of GLatLng objects. For example:
    $pt[0] = new GLatLng(40.689172,-74.044608);
    $pt[1] = new GLatLng(40.826944,-73.928181);
    $pt[2] = new GLatLng(40.755675,-73.84815);

    GLatLng objects can be created using a latitude/longitude like above or an address string:

    $pt[0] = new GLatLng('New York');
  2. Create a GPolyline object, passing in the GLatLng array and setting the line color and weight.
    $line = new GPolyline($pt,"#0000ff",20);
  3. Add the GPolyline to the GMap object.
    $gmap->addPolyline($line);

Geodesic lines follow the curvature of the Earth and represent the shortest distance between two points on the surface of the Earth. They appear as curved lines on a flat map. If you want the lines to be displayed as geodesic lines:

$gmap->geodesic = true;

Polygons

The creation of a polygon is similar to a polyline:

  1. Create an array of GLatLng objects. For example:
    $pt[0] = new GLatLng(40.689172,-74.044608);
    $pt[1] = new GLatLng(40.826944,-73.928181);
    $pt[2] = new GLatLng(40.755675,-73.84815);
    $pt[3] = new GLatLng(40.689172,-74.044608);

    Note that the last point is the same as the first point in the array. This closes the polygon.

  2. Create a GPolygon object, passing in the GLatLng array and setting the color.
    $polygon = new GPolygon($pt,"#0000ff");

    There are additional settings you can specify including different colors for the edge and fill area and the opacity of each as well. See the GPolygon constructor description for more infomration.

  3. Add the GPolygon to the GMap object.
    $gmap->addPolygon($polygon);

Markers & Icons

Markers are used to indicate a location on a map. Each marker has a point (latitude and longitude) and an icon. When a user clicks on a marker icon, an info window is displayed.

You can customize the marker icons and info window contents.

Creating Markers

Create a new GMarker object, passing in an address string:

$marker = new GMarker('2800 East Observatory Road Los Angeles, CA 90027');

You can also pass in a latitude and longitude:

$marker = new GMarker('48.8582992554,2.29437994957');

You add the markers to the GMap, by creating an array of one or more GMarkers and calling the showMap function:

$markers[0] = new GMarker('New York, NY'); 
$markers[1] = new GMarker('Boston, MA'); 
$markers[2] = new GMarker('New Haven, CT'); 

$gmap = new GMap(); 
$gmap->showMap($markers); 

Marker Info Window

By default, the marker's info window will display the address string. You can specify an additional title and URL:

$markers[0] = new GMarker('2800 East Observatory Road Los Angeles, CA 90027',
                          'Griffith Observatory',
                          'http://www.griffithobservatory.org/');

A hyperlink will be created using the title and URL, followed by the address string.

To specify the entire contents of the marker info window, create a string containing the HTML you want displayed. Be sure to use the addslashes function when setting the marker info:

$marker = new GMarker('New York, NY');

$html = '<p>This is some HTML</p>'.
        '<p>This is some more HTML</p>';

$marker->info = addslashes($html); 

Custom Icons

To change the default icon for all markers on the map, create a new GIcon object, specifying the URL to the image you want to use, along with its width and height in pixels, and pass it to the GMap object:

$gmap->icon = new GIcon('http://.../icon.gif', 25, 25);

To change the default icon for a specific marker on the map, set the icon on the GMarker object, instead of the GMap:

$marker->icon = new GIcon('http://.../icon.gif', 20, 20);

Draggable Markers

You can make your markers draggable by the user. For example:

$markers[0] = new GMarker('Miami, FL');
$markers[0]->draggable = true;

If you define a Javascript function called markerDragUpdate(marker, point), this function will be called as the marker is dragged, giving you access to the marker's current latitude and longitude. The marker argument is a Google Map API GMarker object and the point argument is a Google Maps API GLatLng object.

For example, the following function will update a form with the marker's title and current latitude and longitude:

<script language="javascript" type="text/javascript" defer>
<!--
function markerDragUpdate(marker, point) {
        document.myForm.title.value = marker.getTitle();
        document.myForm.lat.value = point.lat();
        document.myForm.lon.value = point.lng();
}
// -->
</script>

<form name="myForm"> 
Title <input type="text" name="title"> 
Lat <input type="text" name="lat"> 
Lon <input type="text" name="lon" value=""> 
</form>  

You can create hyperlinks that will display a marker's info window using the markerLink function. For example:

echo markerLink(0, 'Griffith Observatory', 'gmap');

This will create a hyperlink to marker zero's info window.

Geocoding

Use the getLocation() function to obtain geocode data for any address string recognized by Google as a valid address.

$loc = getLocation('3200 Mount Vernon Memorial Highway, Mount Vernon, Virginia 22121');

To geocode form input, create a form with an address field and hidden lat/lon fields:

<form method="post" action=""> 
Enter Address  
<input type="text" name="address" size="80" onKeyPress="return checkAddressEnter(this.form,event)"> 
<input type="hidden" name="lat"> 
<input type="hidden" name="lon"> 
<input type="submit" value="Submit" onClick="return geocodeForm(this.form);"> 
</form>

Include the necessary form-processing javascript by calling the code322_address_form_js() function.

When the user clicks submit, the Javascript will obtain the latitude and longitude of the entered address and set the hidden values of the form. It will then submit the form to the server.

Error Handling

By default, an alert window will be displayed if an occurs while attemping to display a map. You can ovveride this behavior and handle errors yourself, by turning off error handling and checking for errors in your code. Google Map API key errors will still be displayed in alert windows.

To turn off error handling:

$gmap->handle_errors = false;

Then check for errors after calling showLocation() or showMap():

if ($gmap->error) {
    foreach ($gmap->error_msg as $current) {
        echo $current;
    }
}

For directions, you can check each location using the getLocation() function before calling showDirections().

$fromLocation = getLocation($from);
if ($fromLocation->error) {
    echo 'Error: Code '.$fromLocation->code.' '.$fromLocation->status;
} 

Troubleshooting

Error: file_get_contents

file_get_contents(...) [function.file-get-contents]: failed to open stream: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. in ...gmap.php on line 541

Solution

Edit the gmap_config.php file and set:

define('CURL', true);

Classes

GAdsManager

Specifies settings for AdSense ads on the map.

Constructor

GAdsManager($publisher_id[, $channel[, $max_ads_on_map[, $min_zooom_level]]])

$publisher_idString containing the site's AdSense account.
$channelOptional string containing the AdSense channel used for fetching ads.
$max_ads_on_mapOptional integer specifying the maximum number of ads to display on the map. Default is 3.
$min_zooom_levelOptional integer specifying the minimum map zoom level required to display ads. Default is 6.

Class Members

$enabledBoolean to enable (true) or disable (false) the display of ads. Initial setting is true.
GIcon

This class contains information used to override the default marker icon.

Constructor

GIcon($image[, $width[, $height]])

$imageURL to the image.
$widthOptional width in pixels of the icon. If not specified, 12 is used.
$heightOptional height in pixels of the icon. If not specified, 20 is used.

Class Members

$anchor_xThe x pixel coordinate relative to the top left corner of the icon image at which the icon is acnhored to the map.
$anchor_yThe y pixel coordinate relative to the top left corner of the icon image at which the icon is anchored to the map.
$imageURL to the icon image.
$info_anchor_xThe x pixel coordinate relative to the top left corner of the icon image at which the info window is achnored to the icon.
$info_anchor_yThe y pixel coordinate relative to the top left corner of the icon image at which the info window is achnored to the icon.
$heightHeight in pixels of the icon image.
$widthWidth in pixels of the icon image.
GLatLng

This class contains a latitude and longitude. Arrays of GLatLng objects are used to create GPolyline and GPolygon objects.

Constructor

GLatLng($arg1[, $agr2])

$arg1This contains either an address string or a latitude.
$arg2Optional argument that contains a longitude. If specified, $arg1 is assumed to be a latitude, not an address string.

Class Members

$latThe latitude.
$lngThe longitude.
GLocation

This class contains the data returned from the getLocation function.

Class Members

$streetThe street address of the location.
$cityThe city of the location.
$countyThe county of the location.
$stateThe state/province of the location.
$postal_codeThe postal code of the location.
$countryThe country of the location.
$latThe latitude of the location.
$lonThe longitude of the location.
$codeThe status code returned from the geocode request.
$statusThe status message corresponding to the status code.
GMap

This class is used to create and configure a Google map.

Constructor

GMap([$map_div[, $dir_div[, $api_key]]])

$map_divOptional name of the map div in which to display the map. If not specified, "gmap" will be used.
$dir_divOptional name of the directions div in which to display the driving directions. If not specified, "dir" will be used.
$api_keyOptional Google Map API key. If not specified, the one in the config file is used.

Class Members

$ads_manager GAdsManager used to display AdSense ads on the map.
$enable_dragging Boolean to turn map dragging on/off. Default is true (on).
$error Boolean to indicate that an error occurred.
$error_msg Array of string containing error messages.
$icon GIcon to use for all markers, instead of the default Google Map Icon.
$handle_errors Boolean to control how errors are handled. If true (default) errors are displayed in an alert window.
$key The Google Map API Key to use. If not set, the one in the config file is used.
$locale String containing the locale ("fr","es", etc.)
$map_blowup_type String that contains the initial map type displayed (map, satellite or hybrid) for blowups.
Valid values are 'map','sat', or 'hybrid'. Default is 'map'.
$map_blowup_zoom Integer containing the initial zoom value of the map blowups.
$map_type String that contains the initial map type displayed (map, satellite or hybrid).
Valid values are 'map','sat', or 'hybrid'. Default is 'map'.
$markers
An array of GMarker objects to display.
$show_map_blowup Boolean to turn the map type blowups on/off. When this is on, clicking a map marker will display a zoomed-in map in the info window. Default is false (off).
$show_map_control Boolean to turn map pan/zoom control on/off. Default is true (on).
$show_map_type_control Boolean to turn the map type (Map/Satellite/Hybrid) control on/off. Default is true(on).

$show_markers Boolean to turn location markers on/off. Default is true (on).
$traffic_overlay Boolean to turn traffic information overlay on/off. Default is false (off).
$waypoints An array of integers, each of which is the index of a marker in the marker array ($markers). Each marker that is listed in this array will be added as a waypoint in the driving directions.
$zoom Integer containing the initial zoom value of the map. Default value is 13.

Member Functions

showDirections($loc1, $loc2)

Creates a Google map and directions for the specified locations.

$loc1String containing the start address.
$loc2String containing the end address.

showLocation($addr, $title='', $url='')

Displays the specified address in a map.

$addrString containing an address or lat/lon.
$addrOptional title string to display in the location's marker.
$addrOptional url to display in the location's marker (as a hyperlinked title).

showMap($markers)

Displays a Google map and creates markers for the specified locations.

$markersArray of one or more GMarker objects.
GMarker

This class contains display information for a marker in a Google map.

Constructor

GMarker($address[, $name[, $url]])

$addressString containing either an address or a latitude,longitude.
$nameOptional string containing the name/title of the marker.
$urlOptional string containing a URL for the marker. Used to hyperlink the name/title.

Class Members

$icon Optional GIcon to use for this marker, instead of the default Google Map Icon.
$image Optional string containing the path to an image file. The image will be displayed in the marker.
$info Optional string containing HTML to override the default information displayed in the marker.
$lat Latitude of the marker location. If not specified, latitude will be determined using Google's geocoding service.
$lon Longitude of the marker location. If not specified, longitude will be determined using Google's geocoding service.
$map_blowup_type Map type of marker blowup ('map','sat' or 'hybrid').
$map_blowup_zoom_level Initial zoom level of map blow-up.
$name Optional string containing the name of the location. Used as the title in map marker display.
$show_map_blowup If true, the marker will contain a map-blowup instead of an info window. Defaults to false.
$url Optional string containing a URL, used in with $name to create a hyperlinked title in the map marker.
GPolyline

Specifies a polyline map overlay.

Constructor

GPolyline($points, $color, $weight)

$pointsAn array of GLatLng objects.
$colorThe color of the line, specified as hex, i.e., "#ff0000".
$weightInteger specifying the thickness of the line.
GPolygon

Specifies a polygon map overlay.

Constructor

GPolygon($points, $edge_color[, $weight[, $fill_color[, edge_opacity[, fill_opacity]]]])

$pointsAn array of GLatLng objects.
$edge_colorThe color of the outline/edge, specified as hex, i.e., "#ff0000".
$weightOptional integer specifying the thickness of the line. Default is 3.
$fill_colorOptional fill area color (hex string). If not specified, the edge color is used.
$edge_opacityOptional number between 0 and 1 specify the edge opacity. Default is 1.
$fill_opacityOptional number between 0 and 1 specify the edge opacity. Default is 0.2.

Functions

code322_address_form_js

code322_address_form_js($key = '')

This function generates the Javascript needed for a geocode address field.

Arguments

$keyOptional Google Maps API key. If not specified, the one in the config file will be used.
getLocation

getLocation($address, $key='')

This function returns a GLocation object for the specified address.

Arguments

$addressA string containing an address.
$keyOptional Google Maps API key. If not specified, the one in the config file will be used.

markerLink($num, $text, $div='gmap')

This function generates a string containing HTML for a hyperlink to a marker info window. When the link is clicked, the specified marker's info window is displayed.

Arguments

$numMarker number, corresponds to the marker's index in the GMap->marker array.
$textString containing the text of the hyperlink.
$divOptional name of the div containing the map. If not specified, "gmap" is used.