Third Party Extensions

Google Maps API Tutorial

Draggable EInserts

EInserts supports the GDraggableObject() facility.

Here’s an example.

Unfortunately, GDraggableObject() doesn’t track position changes caused by changes of zoom level, so I disable EInsert draggability when you change the zoom level.

To activate draggability, call the new einsert.makeDraggable() method.

When the dragging is complete, an EInsert “dragend” event is triggered, which returns the new value of einsert.point. This allows you to use draggable EInserts on a development version of your map, position them accurately by dragging, then be notified of the final coordinates which you can then use for the live a with non-draggable EInserts .

Download EInserts from here einsert.js.

Advertisements

Third Party Extensions

Google Maps API Tutorial

Using the EInsert extension

The EInsert extension is implemented as a Custom Overlay.

The EInsert extension allows you to attach a scalable image to the map. The extension scales the image as the zoom level changes.

Here’s an example

You could use EInserts to:

  • add updates to the Google maps (as in that example)
  • draw small complex boundary lines or tracks in a way that runs faster than polylines, and is easier to implement than a custom maptype.
  • add detailed plans of individual facilities.
  • draw circles, like this.

In order to use EInsert you need to:

  1. Create a suitable image. Transparent PNG format is particularly suitable. Animated GIF format is not suitable.
  2. Include a copy of the “einsert.js” file. Please take your own local copy, don’t hot link to my copy of the file.
  3. Create some EInsert objects.
  4. Use map.addOverlay() to add them to the map.

1. Creating a suitable image

I used an image processing package that supports layers, and drew the “Hawking Way” graphic on one layer with a copy of the satellite imagery on another layer.

EInsert assumes that the image can be used with the AlphaImageLoader in IE, so avoid file formats that AlphaImageLoader can’t handle, such as animated GIF.

Make a note of the dimensions of the image and the zoom level it was created to match.

2. Include a copy of the “einsert.js” file

Download it from here einsert.js

Include it like

    <script src="einsert.js" type="text/javascript"></script>

3. Create some EInsert objects

E.g.

      var insert = new EInsert(new GLatLng(53.8,-3.0),
                   "hawkingway.png", new GSize(159,435), 16);

The parameters are:

  1. A GLatLng() specifying the location of the centre of the image.
  2. A string containing the URL of the image.
  3. A GSize() specifying the size of the image.
  4. A number specifying the zoom level on which the image is to be displayed at full size.
  5. (Optional) zindex and pane control value.
    Use -1 if you want this EInsert to be placed below any polylines and GTileLayerOverlay()s.
    use 0 if you want this EInsert to be placed above any polylines and below any GTileLayerOverlay()s.
    Use 1 if you want this EInsert to be placed above any polylines and GTileLayerOverlay()s.
    Use other values to place one EInsert above or below another.

4. Use map.addOverlay() to add them to the map.

And use map.removeOverlay() if you want to remove them.

map.clearOverlays() will also remove all the EInserts as well as any markers and polylines.

Hide and Show

The insert.hide() method makes the EInsert invisible.

The insert.show() method makes the EInsert visible.

The insert.isHidden() method returns true if the EInsert is hidden.

The insert.supportsHide() method returns true, indicating to the API that EInserts support hide(), show() and isHidden().

More Methods

The insert.getPoint() method returns the position of the EInsert.

The insert.setPoint(latlng) method moves the EInsert to a new position.

The insert.setSize(gsize) method changes the size of the EInsert.

The insert.setImage(url) method changes the image of the EInsert.

The insert.setZindex(a) method changes the zIndex of the EInsert relative to other EInserts.

Notes

EInserts are placed below the markers and info windows.

You can click, double-click and drag parts of the map that are underneath EInserts.

You don’t need to keep a reference to your EInserts unless you want to removeOverlay() them, hide() them or change their properties.

Positioning Hint

An easy way to place your EInserts in the correct place is to make them draggable.
See Draggable EInserts

Using EInserts with MarkerManager

EInserts work under the Open Source MarkerManager.

The Open Source MarkerManager can be obtained here http://code.google.com/p/gmaps-utility-library-dev/wiki/Libraries.

MarkerManager can manage EInserts in the same way that it can manage GMarkers.

Here’s an example that uses 1576 EInserts

Third Party Extensions

Google Maps API Tutorial

Animated Markers

From API v2.59, the API supports animated GIFs as markers in all browsersThe techniques described on the rest of this page are no longer necessary

You may have noticed that the API accepts GIF images as markers, but that animated GIF icons don’t work in IE. This is because the API loads the marker image with the “DXImageTransform.Microsoft.AlphaImageLoader” filter under IE, so that transparent PNG files are displayed correctly, and that filter doesn’t handle animated GIFs.

This example  shows three strategies for animating a marker.

The main v1 methods are no longer possible, so the only possibility is to use a third party extension.

The example shows three implementations of clickable animated markers using third party extensions. From left to right:

  1. Pure TLabel
    The contents of the TLabel are an animated GIF.
    addDomListener() is used on the TLabel div to catch mouse clicks and open an info window.
  2. TLabel plus GMarker
    The contents of the TLabel are an animated GIF.
    An invisible GMarker is plotted at the same location. The GMarker mouse target goes above the TLabel to catch the clicks and the GMarker shadow goes underneath.
  3. ELabel plus GMarker
    The contents of the ELabel are an animated GIF.
    An invisible GMarker is plotted at the same location. The GMarker mouse target goes above the ELabel to catch the clicks and the GMarker shadow goes underneath.ELabels overlap intelligently when the “overlap” property is set.

Third Party Extensions

Google Maps API Tutorial

Using the ELabel extension

The ELabel extension is implemented as a Custom Overlay.

ELabel allows you to place text labels or images or any other HTML elements on the map and have them move with the map, like marker and polyline overlays

Here’s an example

In order to use ELabels you need to:

  1. Create CSS class styles for your labels. It is possible to run ELabels without them, but it’s generally easier to use them.
  2. Include a copy of the “elabel.js” file. Please take your own local copy, don’t hot link to my copy of the file.
  3. Create some ELabel objects.
  4. Use map.addOverlay() to add them to the map.

1. CSS Class Styles

Create CSS class styles for your ELabels to use. E.g.

    <style type="text/css">
    .style1 {background-color:#ffffff;font-weight:bold;border:2px #006699 solid;}
    </style>

You’ll probably find it a lot easier to use pre-defined styles.
You’ll usually want to include a background-color style setting, because the default is to have an invisible background.

2. Include a copy of the “elabel.js” file

Download it from here elabel.js

Include it like

    <script src="elabel.js" type="text/javascript"></script>

3. Create some ELabel objects

E.g.

      var label = new ELabel(new GLatLng(44.3,-78.8), "Utopia", "style1");

The parameters are:

  1. a GLatLng() specifying the location.
  2. a html string to be used as the contents of the ELabel.
  3. (optional) a string containing a class name, corresponding to the class style you created in step 1.
  4. (optional) a GSize() specifying a pixel offset from the GLatLng(). Without this parameter, the bottom left corner of the ELabel will touch the location specified by the GLatLng
  5. (optional) an opacity percentage. If omitted, the ELabel will be 100% opaque.
  6. (optional) set this to true to cause ELabels to overlap intelligently. If omitted, the latest one to be addOverlay()ed will be on top.

4. Use map.addOverlay() to add them to the map.

And use map.removeOverlay() if you want to remove them.

map.clearOverlays() will also remove all the ELabels as well as any markers and polylines.

Notes

ELabels are placed above the markers and below the info window.

You can click markers that are underneath ELabels, even if the marker is 100% opaque.

You can click, double-click and drag parts of the map that are underneath ELabels.

You can use different style classes for different ELabels on the same map.

You don’t need to keep a reference to your ELabels unless you want to removeOverlay() them or change their properties.

The content of an ELabel can be as complex as you want. Here’s an example of slightly more complex content.

Manipulating ELabels

When an ELabel is not addOverlay()ed, you can change its properties directly. e.g.

    map.removeOverlay(label)
    label.pixelOffset=new GSize(20,10);
    map.addOverlay(label)

While a label is addOverlay()ed, the following methods can be used to modify its properties dynamically.

  • label.hide() : Makes the label invisible
  • label.show() : Makes the label visible if it was hidden
  • label.setContents(html) : changes the contents of the label.
  • label.setPoint(glatlng) : changes the location of the label.
  • label.setOpacity(number) : changes the opacity of the label.

Using ELabel with MarkerManager

ELabels work under the Open Source MarkerManager.

The Open Source MarkerManager can be obtained here http://code.google.com/p/gmaps-utility-library-dev/wiki/Libraries.

Now that the Open Source MarkerManager is available, I’m not going to be updating ELabels to work under new releases of the obfuscated GMarkerManager. The problem is that I need to know the internal name by which GMarkerManager requests the location of the overlays that it manages. MarkerManager uses overlay.getPoint(), but the obfuscated GMarkerManager changes the internal function name whenever the code is re-obfuscated.

MarkerManager can manage ELabels in the same way that it can manage GMarkers.

Here’s an example that uses 1576 ELabels.

Markered Labels

If you try to place an ELabel alongside every marker, then you can get the the markers to overlap the markers sensibly and the labels to overlap the labels sensibly, but the labels and markers don’t overlap each other sensibly.

What you can do is place an <img> of the marker inside the ELabel contents, so now the marker image and text acts as a single ELabel, and the intelligent overlapping works.

If you care about how the image looks in MSIE6, then you need to to add code to switch to using the AlphaImageLoader if the browser is MSIE. Or you could use a GIF image instead of a PNG.

If you want the markers to be clickable, then place an invisible GMarker at the same location. ELabels are not clickable, so the click drops through to the GMarker below it.

Here’s an example.

Just for fun, I bump up the opacity of the label when the info window is open on the GMarker associated with it. You could do the same thing with mouseover and mouseout events on the GMarker.

Bugs

IE sometimes seems to return false information about the height of the ELabel contents. This causes the vertical positioning of the ELabel to be incorrect.

Updates

v0.2: 5 April 2006: ELabel.copy() fixed. The labels now get copied correctly into .showMapBlowup()’s.
(Thanks to “Jacob” for pointing out the problem)

v1.0: 7 April 2006: Lots of new methods added

v1.1: 31 Dec 2006: Works with GMarkerManager under API v2.67 to v2.71

v1.2: 25 Feb 2007: Works with GMarkerManager under API v2.67 to v2.75

Third Party Extensions

Google Maps API Tutorial

Using Jef Poskanzer’s OverlayMessage

OverlayMessage allows you to place a semi-transparent message over the top of any HTML element. It’s not a true Google API Map extension, because it works equally well on things other than maps.

It can be useful for Google Maps that take a while to load. You can display the message before the map starts to load, and clear it in the <body onload> function, if you’re not using onload for anything else.

Here’s an example

Full details of how to use it are at http://www.acme.com/javascript/#OverlayMessage

Third Party Extensions

Google Maps API Tutorial

Jef Poskanzer’s Clusterer

If you happen to have thousands of points that you want to plot, you’ll find that the map becomes too slow to be usable. One way round this, without a server side database, is to use Jef Poskanzer’s excellent Clusterer.js.

See http://www.acme.com/javascript/#Clusterer

Here’s an example

Instead of displaying the markers directly, you tell the Clusterer about them, and it monitors the map movements and zoom level and determines when it is appropriate to display icons that indicate clusters, and when it is appropriate to display individual markers.

Jef has asked me not to describe how to use Clusterer, so I won’t.

Parameters

If you don’t like the default Clusterer settings, then you can set some parameters.

  • clusterer.icon
    can be set to the GIcon to be used to indicate a cluster, so you can use your own marker icon to match the rest of your page.
  • clusterer.maxVisibleMarkers
    sets the maximum number of icons that will be displayed at any one time. The default is 150.
  • clusterer.gridSize
    sets the size of the grid used for placing the clusters. The default value of 5 indicates that there can be 5 clusters from east to west across the map.
  • clusterer.minMarkersPerCluster
    sets the minimum number of markers that can be in a cluster. The default value is 5.
  • clusterer.maxLinesPerInfoBox
    sets the number of detail lines that will be displayed in the info window associated with a cluster. If you’ve got a small map, then you may need to reduce this to prevent the cluster info boxes being too large for your map. If there are more markers in a cluster than this value, then the info window adds a line that says “.. and XXX more”. The default value is 10.

You don’t have to set any of these parameters, the Clusterer works perfectly well with the default settings.

Third Party Extensions

Google Maps API Tutorial

Third Party Extensions

This is a list of all the third party extensions that I know about.

Clusterer Handles large numbers of markers.
OverlayMessage Place a semitransparent message over a map.
ELabels Place any html element on a map (good for text labels)
GxMagnifier Adds a moveable magnified window
GxMarker Provides markers with built in tooltip support and hover events
EInsert Attach an image to the map that scales when the map zooms
EWindows Multiple custom info windows
PDMarker Change marker images, show tooltips on hover, customised info windows, manage lists of markers, store marker data, etc.
Custom Tile Generator Generates tiles from an XML description
GRoutes Provides functionality for displaying multiple routes
BpBrowser Exposes browser and Operating System info
BpDownloadUrl Like GDownloadUrl but with more options
BpLabel Place any html element on a map (good for text labels)
BpMarker Extended Marker class with tooltip and mousover icon swapping
BpMarkerLight Extended Marker class with tooltip and mousover icon swapping
BpMarkerList Automatic sidebars.
BpWindow Display info in a box that can extend outside the map.
BpControl Simple interface to GControl.
MapTypeMenuControl A compact map type control
MarkerManager An improved Open Source version of GMarkerManager
LabeledMarker Puts text onto markers
EGeoXml Renders My Maps KML files and other similar KML files.
HtmlControl HtmlControl provides an easy way to add and position custom GControls over your Google Map.
EPoly Adds a few methods to polygons and polylines.
ASP.NET Control Write Google Maps with ASP.NET code instead of Javascript
EBubble An alternative to info windows
GeoXml Renders KML, GML, GPZ and GeoRSS files.
Blocks Simplified markers. Faster than GMarkers.
Graticules Display lat/lng grid or UK National Grid.
Arrows Displays small arrows using SVG or VML.
Offsetable Marker A draggable marker that leaves a line pointing back to where it came from.
Scaled Circle Displays a scaled circle using SVG or VML.
Clickable Polylines and Polygons Displays clickable polylines and polygons using SVG or VML.
Distance to Poly Calculates the distance of a point from a polyline or the boundary of a polygon.
Calculate US OS references Calculates UK Ordnance Survey map references.
ExtInfoWindow Customised Info Window
GMouseWheelControl Extra mouse functionality
ClusterMarker Detects and substitutes markers that would overlap
Bearings and Directions Functions for distances, bearings, rhumb lines, etc.
GeoKit A Rails plugin
USNaviguide_Google_Tiles A Perl module that calculates tile details
jMaps jQuery plugin for Google Maps
Parallel Lines Creates a pair of parallel polylines
MStatusControl Displays map centre, SW and NW corners, zoom level and mouse position (tile numbers, (x,y) position and lat/lon)
MapIconMaker Easily create dynamically sized and coloured icons.
MarkerTracker Display directional indicators for markers as they move out of a maps view.
GReverseGeocoder Reverse Geocoder
ourarea allows you to easily create an embeddable Google Map showing the area around your business that you deliver to or support.
EShapes provides a number of additional static methods for GPolyline and GPolygon for creating certain shapes
Frame Animation Frame animation overlay
MControl Suite A bunch of custom controls.
cSnapToRoute Snap a marker to the closest point in a polyline
ProgressbarControl Progress bar control
NASA Maps NASA Extensions to the Google Maps API
Geometry Controls Edit content just like My Maps
CSGeoXml Renders KML files as a single overlay.
Intellisense Helper Intellisense helper for VS2008.
ClusterManager Substitutes markers that would overlap with clusters.
Popup Title A little popup for GMarkers
Dragzoom Zoom by dragging a rectangle on the map
ExtLargeMapControl Custom Large Map COntrol that uses the new graphics
ExtMapTypeControl Adds overlay controls that look like map type controls
SnapToRoute Snap a marker to closest point on a line.
MultiIconMarker Change marker icon when an event occurs
MyMapExplorer Embed MyMaps in your web page
Custom Marker Maker Creates suitable files for a custom marker.

Clusterer

Allows you to use large numbers of markers by collecting them into “clusters” to avoid having too many markers drawn on the screen at any time.
Author: Jef Poskanzer

Example page: http://www.acme.com/jef/hotsprings/ and my example

Information: http://www.acme.com/javascript/#Clusterer and my tutorial

OverlayMessage

OverlayMessage allows you to place a semi-transparent message over the top of any HTML element. It’s not a true Google API Map extension, because it works equally well on things other than maps.
Author: Jef Poskanzer

Example page: my example

Information: http://www.acme.com/javascript/#OverlayMessage

Elabels

ELabels allow you to place any HTML element on a map as a Custom Overlay. You can use it in a similar manner to TLabel.
Author: Mike Williams

Information: my tutorial

Example Page:my example

GxMagnifier

GxMagnifier is a free add-in control for Google Maps that creates a moveable, magnified window on top of your map.
Author: Richard Kagerer

APIv2 compatibility: Andre Howe

Example page: boxme.net/wdch/test.html

Download: boxme.net/wdch/GxMagnifier2.js

Information (v1 version): http://www.googlemappers.com/libraries/gxmagnifier/docs/default.htm

GxMarker

Provides markers with built in tooltip support and hover events.
Author: J. Shirley

APIv2 compatibility: Robert Aspinall

Information: code.toeat.com/package/gxmarker

EInsert

The EInsert extension allows you to attach a scaleable image to the map. The extension scales the image as the zoom level changes.
Author: Mike Williams

Information: my tutorial

Example Page:my example

EWindows

The EWindows extension provides some of the functionality of Custom Info Windows.
You can design your own info window styles, and have more than one EWindow open on the same map.

Author: Mike Williams

Information: my tutorial

Example Page: my example

PdMarker

PdMarker is a Javascript extension to Google Maps markers. You can change marker images, show tooltips on hover, customised info windows, manage lists of markers, store marker data, etc.
Author: Peter Jones

Information: http://www.pixeldevelopment.com/pdmarker.asp

Example Pages:www.pixeldevelopment.com/virtualgoogleearth.asp
http://www.pixeldevelopment.com/showmap.asp?gallery=stanleypark2004&caller=index.asp

Custom Tile Generator

This Windows desktop application accepts XML files that describes shapes (beziers, closed curves, curves, ellipses, images, polygons, polylines, rectangles, text and filled shapes) and generates a set of tiles suitable for using in a custom GTileLayer.
Author: Jacob Reimer

Information: http://www.reimers.dk/blogs/jjrdk/archive/2006/04/14/216.aspx and http://www.reimers.dk/blogs/jjrdk/archive/2006/05/09/252.aspx

Example Page: http://www.reimers.dk/demos/wmsdemo.aspx

GRoutes

GRoutes is a JavaScript package that provides functionality for displaying multiple routes (including an associated set of markers) on a map along with a control to switch between maps. Informational texts on the markers to be displayed in the info window (bubble) are also supported.
Author: Holger Pollmann

Information: http://www.stud.uni-giessen.de/~st8632/misc/internet/googlemaps.html

Example Page: http://www.stud.uni-giessen.de/~st8632/misc/internet/groutesdemo.html

BpBrowser

Encapsulates browser, os, and version information. Free for commercial and non-commercial use.
Author: Bitperfect Internet Solutions

Information and examples: http://www.gmaptools.com

BpDownloadUrl

A more fully-featured version of GDownloadUrl, allowing you to execute POST and synchronous AJAX requests. Free for commercial and non-commercial use.
Author: Bitperfect Internet Solutions

Information and examples: http://www.gmaptools.com

BpLabel

A robust GOverlay subclass. Lets you put HTML on the map as an overlay. Free for non-commercial use.
Author: Bitperfect Internet Solutions

Information and examples: http://www.gmaptools.com

BpMarker

A GMarker subclass with a few extra options. Free for non-commercial use.
Author: Bitperfect Internet Solutions

Information and examples: http://www.gmaptools.com

BpMarkerLight

A light-weight GOverlay subclass with image and icon swapping, tooltip support, etc. The fact that it’s light-weight allows you to add hundreds of markers to a map quickly. Free for non-commercial use.
Author: Bitperfect Internet Solutions

Information and examples: http://www.gmaptools.com

BpMarkerList

Encapsulates a map sidebar which holds divs which represent markers. Allows for sorting, managing div content and events through the use of HTML templates, and more. Free for non-commercial use..
Author: Bitperfect Internet Solutions

Information and examples: http://www.gmaptools.com

BpWindow

An infoWindow-type tool which can open outside the map. As a result, the map will never automatically pan to show its contents. It also can open outside of its iframe, and open up, right, left, or down, depending on what direction will allow it to open within existing page borders. Free for non-commercial use.
Author: Bitperfect Internet Solutions

Information and examples: http://www.gmaptools.com

BpControl

A simple interface to GControl()
Author: Bitperfect Internet Solutions

Information and examples: http://www.gmaptools.com

MapTypeMenuControl

A compact drop-down map type control.
Author: Dawn Endico

Information and examples: maps.tafoni.net/MapTypeMenuControl/

MarkerManager

Improved version of GMarkerManager.
As well as doing everything that GMarkerManager does, the Open Source version allows markers to be removed, has some bug fixes, and can be used to manage custom overlays, such as ELabels and EInserts, as well as GMarkers.

Author: Doug Ricket, others

Information and examples: code.google.com/p/gmaps-utility-library-dev/wiki/Libraries/

LabeledMarker

Supports markers with textual labels.
Author: Mike Purvis

Code and example: gmaps-utility-library.googlecode.com/svn/trunk/labeledmarker/

Hint: LabeledMarker works well alongside MapIconMaker, like this

EGeoXml

The EGeoXml extension renders My Map KML files and other KML files of similar structure. The internal structures are exposed, allowing you to have much more control than when using GGeoXml.
Author: Mike Williams

Information: my tutorial

Example Page: my example

HtmlControl

HtmlControl provides an easy way to add and position custom GControls over your Google Map.
An HtmlControl can contain any valid HTML markup and can be styled with any valid CSS style-rules.
HtmlControl makes it easy to create; buttons, hideable menus and forms, map loading messages and much more!
Author: Martin Pearman

Information: googlemapsapi.martinpearman.co.uk/htmlcontrol

Example Page:googlemapsapi.martinpearman.co.uk/htmlcontrol/demo_map.php

EPoly

Author: Mike Williams
Adds methods to GPolygon and GPolyline for determining the area, bounds, path length and whether a GLatLng is contained within the poly.

Information: my tutorial

Example Page: my example

ASP.NET Control

Author: Subgurim
Code and information: en.googlemaps.subgurim.net

EBubble

The EBubble extension provides an alternative to info windows.
Author: Mike Williams

Information: my tutorial

Example Page: my example

GeoXml

The GeoXml extension enables client-side parsing and viewing of a number of flavors of GeoXml, including GML from WFS servers, GPX from GPS devices or log as well as KML and multiple flavors of GeoRSS,In addition to the XML it supports saving out and re-loading of KJSON.
Author: Lance Dyas

Information and example: http://www.dyasdesigns.com/geoxml

Blocks

These are a very simple coloured block marker with a tooltip. The point of these is that for the same load time, you should be able to use more of these on a map than you can GMarkers.
Author: “Bill Chadwick ”

Information: http://www.bdcc.co.uk/Gmaps/BdccGmapBits.htm

Graticules

Display lat/lng grid or UK National Grid.
Author: “Bill Chadwick ”

Information: http://www.bdcc.co.uk/Gmaps/BdccGmapBits.htm

Arrows

Displays small arrows using SVG or VML.
Because this extension relies on SVG or VML, it will not work in browsers which do not support these features.

Author: “Bill Chadwick ”

Information: http://www.bdcc.co.uk/Gmaps/BdccGmapBits.htm

Offsetable Marker

This uses sub-classing on GMarker to provide a marker that can be dragged from its spot but leaves a line indicating its actual reference point.
Author: “Bill Chadwick ”

Information: http://www.bdcc.co.uk/Gmaps/BdccGmapBits.htm

Scaled Circle

Displays a scaled circle using SVG or VML.
Because this extension relies on SVG or VML, it will not work in browsers which do not support these features.

Author: “Bill Chadwick ”

Information: http://www.bdcc.co.uk/Gmaps/BdccGmapBits.htm

Clickable Polylines and Polygons

Displays clickable polylines and polygons using SVG or VML.
Because this extension relies on SVG or VML, it will not work in browsers which do not support these features.

Author: “Bill Chadwick ”

Information: http://www.bdcc.co.uk/Gmaps/BdccGmapBits.htm

Distance To Poly

Calculates the distance of a point from a polyline or the boundary of a polygon.
Author: “Bill Chadwick ”

Information: http://www.bdcc.co.uk/Gmaps/BdccGmapBits.htm

Calculate US OS references

Converts Lat/Lng pairs to UK Ordnance Survey references, like “SU 66277 62491”.
Author: “Bill Chadwick ”

Code: http://www.bdcc.co.uk/Gmaps/LatLngToOSGB.js

ExtInfoWindow

Customised Info Window.
Author: Joe Monahan

Information and examples: gmaps-utility-library.googlecode.com/svn/trunk/extinfowindow/.

GMouseWheelControl

A custom control built by using Google Map API to enhance the usage of a mouse on Google Map. It can be used in any Google map mashups. It takes advantage of scroll wheel mouse.
Author: Pman (Parvez Akkas)

Information and Example: http://www.pmanslab.com/projects/gmwControl/.

ClusterMarker

ClusterMarker detects any group(s) of two or more markers whose icons visually intersect when displayed. Each group of intersecting markers is then replaced with a single cluster marker. The cluster marker, when clicked, simply centres and zooms the map in on the markers whose icons previously intersected.
Author: Martin Pearman

Information and Example: googlemapsapi.110mb.com/clustermarker/.

Bearings and Directions

Not actually an extension, but a collection of useful functions
Distance between two points (using Haversine formula).
Distance between two points (using Vincenty formula).
Bearing of one point from another.
Midpoint between two points.
Destination point given distance and bearing from start point.
Rhumb lines
Convert between degrees-minutes-seconds and decimal degrees
Convert between UK Ordnance Survey grid reference and lat/long.

Author: Chris Veness

Information and code: http://www.movable-type.co.uk/scripts/latlong.html.
and http://www.movable-type.co.uk/scripts/latlong-vincenty.html.
and http://www.movable-type.co.uk/scripts/latlong-gridref.html.
GeoKit

Geokit is a Rails plugin for building location-based apps. It provides geocoding, location finders, and distance calculation in one cohesive package. If you have any tables with latitude/longitude columns in your database, or if you every wanted to easily query for “all the stores within a 50 mile radius,” then GeoKit is for you.
Authors: Bill Eisenhauer and Andre Lewis

Information and Examples: geokit.rubyforge.org.

USNaviguide_Google_Tiles

A Perl module that calculates just about everything you’d want to know about tiles including:
Tile name for a coordinate (lat,lng)
Tile name for a pixel location (x,y)
Tiles for a bounding box of coordinates and zoom
Bounding box for a tile in coordinates
Bounding box for a tile in pixel locations
Coordinates to pixel
Pixel to coordinates
Author: John D. Coryat
Information and Code: http://www.usnaviguide.com/google-tiles.htm.

jMaps

jQuery plugin that provides several useful functions that make working with Google maps easier.
Author: Tane Piper

Code: hg.digitalspaghetti.me.uk/jmaps/.

Documentation: hg.digitalspaghetti.me.uk/jmaps/raw-file/271365e77c35/docs/index.html.

Parallel Lines

Creates parallel polylines.
Author: Bill Chadwick

Code: wheresthepath.googlepages.com/BDCCParallelLines.js.

Example: wheresthepath.googlepages.com/ParallelLines.htm.

MStatusControl

displays map centre, SW and NW corners, zoom level and mouse position (tile numbers, (x,y) position and lat/lon)
Author: Marcelo Montagna

Source and Example: maps.forum.nu/gm_MStatusControl.html.

MapIconMaker

Easily create dynamically sized and coloured icons.
The icon images are generated dynamically using a secret feature of the Google Chart API.

There’s a Wizard to help you choose the settings, and a Blog article with details and examples.

(The URL of the Wizard changes from time to time. If the wizard link fails, use the blog link and go from there.)

As well as generating the image, IconFactory also produces correct shadows, click targets, and printImages.

Author: Pamela Fox

Source and Examples: gmaps-utility-library.googlecode.com/svn/trunk/mapiconmaker/

Hint: LabeledMarker works well alongside MapIconMaker, like this (now probably obsolete, because MapIconMaker v1.1 includes createLabeledMarkerIcon)

MarkerTracker

Display directional indicators for markers as they move out of a maps view.
There’s a Blog article with details and examples.

Author: Dan Rummel

Source and Examples: gmaps-utility-library.googlecode.com/svn/trunk/markertracker/

GReverseGeocoder

Given latitude and longitude coordinates, the reverse geocoder obtains the nearest address
Author: Nico Goeminne

Information: nicogoeminne.googlepages.com/documentation.html

ourarea

Allows you to easily create an embeddable Google Map showing the area around your business that you deliver to or support.
Author: Nirmal Patel

Website: http://www.nirmalpatel.com/ourarea/

EShapes

The EShapes extension provides a number of additional static methods for GPolyline and GPolygon for creating certain shapes. It also provides two functions that can help in the placement of such shapes.
Author: Mike Williams

Information: my tutorial

Example Page: my example

Frame Animation Overlay

Author: “bratliff”
Useful for animated overlays, like moving weather radar images.

Please make your own copy because the one on this page may change.

Code: http://www.polyarc.us/frameanimation.js

Example Page: http://www.polyarc.us/ridge

MControl Suite

A bunch of custom controls.
MMapTypeControl
MOpacityControl – With a separate slider foreach tile layer
MZoomControl – Allows for predefined zoom levels
MStatusControl – Displays map status and mouse position info
MTileNumberControl – Displays tile numbers over the map
Author: Marcelo Montagna
Information and example: maps.forum.nu/gm_custom_controls.html

cSnapToRoute

Snap a marker to the closest point in a polyline
Author: Bill Chadwick

Information and example: wheresthepath.googlepages.com/cSnapToRouteDemo.html

ProgressbarControl

Progress Bar Control
Author: Björn Brala

Information and example: gmaps-utility-library.googlecode.com/svn/trunk/progressbarcontrol/

NASA Maps

Extra map types for the Moon and Mars, including polar maps.
Author: NASA

Info: ti.arc.nasa.gov/projects/planetary/maps.php

As supplied, the polar map projections don’t support polylines or polygons.

If you want to draw polylines, then you can use this version of the code: nasamaps2.js which uses a nasty hack to work round the bug in the API. If you’re not using polylines, then use the NASA version of the code, because i’t likely to be faster and to be kept up to date with new imagery.

Here’s an example of a NASA Polar map with polylines.

Geometry Controls

Edit content just like with My Maps.
Author: Chris Marx and Pamela Fox and others

Example: gmaps-utility-library-dev.googlecode.com/svn/trunk/geometrycontrols/examples/test.html

Info: gmaps-utility-library-dev.googlecode.com/svn/trunk/geometrycontrols/docs/reference.html

Code: gmaps-utility-library-dev.googlecode.com/svn/trunk/geometrycontrols/

CSGeoXml

A modified version of EGeoXml that acts like a single overlay.
Author: Matt Bernier

Information: devblog.cloudsync.com/projects/csgeoxml/

Intellisense Helper

Intellisense helper for VS2008.
Author: Nicolas Boonaert & Roger Chapman

Information: http://www.codeplex.com/GMapJS

ClusterManager

ClusterManager detects any groups of two or more markers whose icons visually intersect when displayed. Each group of intersecting markers is then replaced with a single cluster marker. The cluster marker, when clicked, provides an info window that gives access to the original markers.
Author: Peter van der Zee

Information and Example: cm.qfox.nl.

Popup Title

Displays a popup mini bubble for marker mouseover titles.
Author: Masashi Katsumata

Information and Example: googlemaps.googlermania.com/gmapkit/example/GMarkerPopupTitle.html.

Dragzoom

Dragzoom is a custom Google Maps control which allows you to zoom by dragging a rectangle on the map.
Author: Andre Lewis

Information and examples: gmaps-utility-library.googlecode.com/svn/trunk/dragzoom/

ExtLargeMapControl

A custom Large Map COntrol that uses the new graphics, as seen on maps.google.com.
Author: Bjorn Brala

Information and examples: gmaps-utility-library.googlecode.com/svn/trunk/extlargemapcontrol/.

ExtMapTypeControl

ExtMapTypeControl lets you add a control to the map which looks like the typical GMapTypeControl from the obfuscated API. By specifying additional options however, you can also add a Traffic button to the control and a drop-down legend for that button. Author: Pamela Fox and others
Information and examples: gmaps-utility-library.googlecode.com/svn/trunk/extmaptypecontrol/.

SnapToRoute

SnapToRoute will snap a marker to closest point on a polyline.
Author: Bjorn Brala

Information and examples: gmaps-utility-library.googlecode.com/svn/trunk/snaptoroute/.

MultiIconMarker

An alternative for GMarker that allows the associated GIcon to be changed (not just the icon image) when an event occurs.
Hint: by using your own custom events you can achieve the equivalent of a .setIcon() method.

Author: Masashi Katsumata

Information and examples: gmaps-utility-library-dev.googlecode.com/svn/trunk/multiiconmarker/.

MyMapExplorer

Allows you to embed a map created using Gooogle Maps’ My Maps feature into any web page with more information and flexibility than Google’s iFrame embed code.
Author: John Beales

Information and examples: code.google.com/p/mymapexplorer.

Custom Marker Maker

Upload an image (png, gif, jpg) and this page creates the 6 separate image files (image, shadow, printImage, mozPrintImage, printShadow and transparent) that make up a custom marker icon and suggests an array of x,y pixel coordinates that define the image map area used for capturing image clicks in non IE browsers. Transparency of the original image is preserved. Users see their image as a marker on a map and are presented with a zipped package for download that contain the generated images and some sample code.
Author: Graham

URL: http://www.powerhut.co.uk/googlemaps/custom_markers.php.

Custom Maps

Google Maps API Tutorial

Browser Connection Limits

Inspiration

This page was inspired by the fact that Google seem to have imposed timeouts on the tile fetches. That’s fine for Google tiles that are provided by fast servers, but if you have a slow server, it looks like the API doesn’t always wait long enough before giving up and deciding that the fetch has failed.

I noticed that fetching an individual tile from a page that exhibits the problem wasn’t much any longer than fetching an individual Google tile. The significant difference was that the Google map types were fetching more tiles at once, so the total time taken to fetch all the tiles was significantly shorter. Google achieve this effect by using aliases to break the browser connection limits.

What are Browser Connection Limits?

Although browsers are capable of fetching many files simultaneously, only two files will be fetched simultaneously from the same domain. This limit made some sense back in the days when the majority of Internet users had slow dial-up connections, but it makes no sense with today’s high speed connections. For most pages, the continuing existence of these limits doesn’t slow the page loading down to make it worthwhile for the limits to be redesigned, but they do have a significant effect on map tile fetches.

So what can we do?

What Google do is have four different subdomains mt0.google.com, mt1.google.com, mt2.google.com, mt3.google.com, and share the tile fetching between them. The browser doesn’t know that these are all aliases for the same machine, and allows two simultaneous fetches to each subdomain. So eight tiles get fetched at the same time, instead of two.

Here’s an example where I spread the load across four subdomains of econym.org.uk.

The code looks like this

      CustomGetTileUrl=function(a,b){
        var subdomain=(a.x+a.y)%4;
        return "http://sub" +subdomain+ ".econym.org.uk/gmap/tiles/"+a.x+"_"+a.y+"_"+(17-b)+".jpg"
      }

The rest of the code is the same as that used in custommap1.htm.

I created “sub0.econym.org.uk” etc., as subdomanins that have the same destination (or “Document root”) as “econym.org.uk”, so there actually is only one set of tiles on the webserver, but the browser has no way of knowing that.

How much faster is it?

In those examples, you may not notice much speed difference visually, but when the pages are analysed with PageTest, the old one typically loads in 4.5 seconds and the new one in 3.4 seconds.

Even then, that doesn’t seem like a huge improvement, but if you compare the timings from the start of the first tile request to the completion of the last tile request, those times have gone down from 2.9 seconds to 1.4 seconds. If you have a slow server, the differences would be expected to be more significant.

The timings

I don’t know how long PageTest keeps the timing results, but for now you can see one set of results for the custommap1 at pagetest.patrickmeenan.com:8080/result/RC8/1/details/ and for custommap1p atpagetest.patrickmeenan.com:8080/result/RC7/1/details/

Custom Maps

Google Maps API Tutorial

Alternative Map Type Controls

New formats for the map type controls were introduced in v2.93 and v2.94. These new formats can be useful in situations where you have a large number of custom map types, causing the normal GMapTypeControl to become cumbersome.

The GMenuMapTypeControl() displays all the map types in a drop-down menu.
If the optional first parameter is true, then shortnames are used.
If the optional second parameter is true, then a border is drawn round the control.

The GHeirarchicalMapTypeControl() lists “child” map types below their “parent” map type if that parent is active.
If the optional parameter is true, then shortnames are used.

GHeirarchicalMapTypeControl() has three Methods for managing parent and child map type relationships:

GHierarchicalMapTypeControl.addRelationship(parent, child, name, isDefault) adds a parent/child map type relationship. The parameters are

        1.  parent GMapType
        2.  child GMapType
        3.  (optional) Name for child
        4.  (optional) isDefault boolean

GHierarchicalMapTypeControl.removeRelationship(child) removes a parent/child map type relationship. The parameter is the child GMapType.

GHierarchicalMapTypeControl.clearRelationships() removes all relationships.

Here’s an example of a map with seven map types showing all possible map type controls. Click the buttons to display the different controls.

Here’s an example that sets the map type controls to look exactly like the v2.94 maps.google.com controls. The Terrain map type is added. Hybrid is underneath Satellite and is selected by default when the Sattelite button is clicked.

Custom Maps

Google Maps API Tutorial

Using Google Maps API for Flat Maps and Diagrams

You might think that we can use the techniques in the previous examples to get the Google Map API to manage views of things that are not spherical maps, such as flat maps, diagrams and circuit boards. That would be fine as long as we don’t want to draw markers or polylines on it.

Once we start drawing lines, we encounter the fact that all the maps we’ve looked at so far use the Mercator projection, which distorts the mapping geometry in order to represent a spherical Earth on a flat map.

The line on the “Mercator” map type in this example is a “straight” line that gets distorted into a curve due to the Mercator projection. You can imagine that such a distortion wouldn’t be much use for dealing with things like circuit diagrams.

The “Euclidean” map type in the same example Note I don’t move or redraw the markers or the polyline. When the map type changes, the API redraws all the overlays using the new projection.

Copyright strings

The GTileLayer.getCopyright() method must return an Object that has the following properties

prefix String to be placed at the front of the copyright text, like “Map Data:” or “Satellite Imagery:”
copyrightTexts Array of strings: Copyright texts that apply to various parts of the area.

The constructor and methods of the object class are not exposed, so it’s not possible to construct the return value properly, but it is possible to return an anonymous object literal.

E.g., in the example, I’ve used

     tilelayers[0].getCopyright = function(a,b) {
        return {prefix:"Fractal: ©", copyrightTexts:["Mike Williams"]};
     }

Potential Pitfalls

  1. The GScaleControl() and point.distanceFrom() features assume spherical geometry, so they’re not going to be useful for non-Mercator maps.
  2. The API calculates the polyline geometry at zoom level 17. This means that any GProjection used in a map that has polylines must be created with at least 18 zoom levels, even if the map itself has far fewer zoom levels.

Custom Maps

Google Maps API Tutorial

Custom Map Types

To create a custom map, you first need to create a set of 256*256 tiles, or obtain a set for which you have the relevant permissions. Or, alternatively, write your own tileserver code that runs on your server and can create the tile images on the fly.

A Simple Custom Map

To use these tiles as a simple Custom Map Type, you need to do following:

  • Create a GCopyright object
  • Create a GCopyrightCollection
  • Add the GCopyright to the GCopyrightCollection
  • Create a GTileLayer object
  • Create a GMapType object
  • Add the GMapType to the map

These steps are well described in The Mapki so I’ll not repeat that information here.

Here’s an example.

The only significant difference between this example and the Makpki information is that my tiles are stored as images in my web folder, rather than being generated by a tileserver script.

Aligning your map

There’s a very nice facility at open.atlas.free.fr/GMapsTransparenciesImgOver.php which can be used to align a map image in the correct place on top of a Google map.

It specifies the preprocessing (scaling and padding) that should be performed on your image before using something like the Automatic Tile Cutter mapki.com/wiki/Automatic_Tile_Cutter to cut your image into tiles.

Bounds checks

One problem with the previous example is that it causes the API to perform standard error tile handling when the user drags the map out of the custom region. This is a bit ugly and slow.

So what we can do is to add a check in the CustomGetTileUrl() code to see if the tile is in the custom region, and if not return a special “blank.jpg” tile.

Here’s an example.

It would have been nice to have been able to store the information about the custom region tiles in a series of GBounds() objects (one for each supported zoom level) and test to see if the GPoint() representing the tile number is inside the GBounds(), but there is no GBounds.contains(point) method.

Bounds Checks 2

Instead of returning a blank tile for tiles that are outside the custom region, you could return the URL of a tile from G_NORMAL_MAP or G_SATELLITE_MAP.

The problem with this is that you should then display the Google copyright string whenever a Google tile is visible. This turns out to be extremely tricky to get right.

In this example, I display the custom copyright string whenever a custom tile is visible and the Google copyright string whenever no custom tiles are visible.

If you know a better way of handling the copyright, please let me know atlas@econym.demon.co.uk

Common CustomGetTileUrl formats

This code returns URLs in the format created by the Photoshop tile splitter: “http://mydomain.com/tiles/5295_5922_3.jpg&#8221;

      CustomGetTileUrl=function(a,b){
          return "http://mydomain.com/tiles/"+a.x+"_"+a.y+"_"+(17-b)+".jpg";
      }

This code returns URLs in the format created by the Paint Shop Pro tile splitter: “http://mydomain.com/tiles/14_5922x5295.jpg&#8221;

      CustomGetTileUrl=function(a,b){
          return "http://mydomain.com/tiles/"+b+"_"+a.y+x+a.x+".jpg";
      }

This code returns URLs in the format used by the Google Normal Map tileserver: “http://mydomain.com/tileserver.php?x=5295&y=5922&zoom=3&#8221;

      function CustomGetTileUrl(a,b) {
        var z = 17 - b;
        var f = "http://mydomain.com/tileserver.php?x="+a.x+"&y="+a.y+"&zoom="+z;
        return f;
      }

Potential Pitfalls

  1. Some API features, such as polylines and ground overlays, perform their calculations at zoom level 17, rather than at the max zoom level of the map type. These features will fail if the GProjection() of the map type ahs less than 18 zoom levels.

More advanced stuff

Google Maps API Tutorial

UK Posctcodes

The Problem

Since I wrote this page, The Problem seems to have gone away making this page unnecessary

Unlike other countries, the geographical information associated with UK postcodes is strictly controlled. The copyright is owned by the Royal Mail, who make a lot of money selling licences to use it.

For example, I just bought a new TV. The guy at the shop didn’t ask for my address, but just asked for my postcode and house number, and used that to find my full street address. The shop presumably finds it worthwhile fo pay the annual £85 licence per workstation, or the annual £75,000 corporate licence for all the workstations operated by that chain of stores, or one of the intermediate licences. Since large numbers of UK high street shops do the same thing, that adds up to an awful lot of money that the Royal Mail receive from licensing that data. Therefore they’re not keen to allow Google to give the information away for free via the API geocoder.

The Royal Mail have allowed Google to buy a licence to use the data on its own websites, but not to redistribute the data to other people.

This results in it being possible to find the exact location of “FY2 0HH, UK” at maps.google.com, but if you try the same search with the API geocoder you get a point that’s nearly a mile away.

What actually happens

The API geocoding database contains the locations of places like “FY2 0” and “FY2 9”. I.e. the “outcode” part of the postcode plus the numeric part of the “incode”.

When you reverse geocode a point, it gives the correct one of those locations as the Locality.PostalCode.PostalCodeNumber

When you forward geocode a UK postcode, the geocoder is only allowed to look at the “outcode” part. It then returns an arbitrary one of the “FY2 ?” locations, not necessarily the correct one. Which one of those locations actually gets returned is influenced ny things like country bias. There is a suggestion that it might even be biassed by the location of the user who is calling your page.

Workrounds

Use the full address

You could always ask your user to input their full address. That generally works.

The terms of the licence require the geocoder to discard the “incode” part of the postcode, and effectively performs a search for [street address] near [outcode]. In some extreme cases, even that won’t work. An example near where I live is “10 Bispham Road FY6 7PE, UK”. There are three “Bispham Road”s that are near FY6. One at “FY3 7HJ”. One at “FY5 1DG” and the one that I asked for at “FY6 7PE”. The API geocoder returns all three, but the one I asked for is the second placemark.

Use a non-google geocoding service

I don’t know of any commercial on-line services, but I’m sure there are some.

Buy the data from the Royal Mail

Put it on your server and perform your own lookups. I reckon that you need to pay the annuall £3,850 fee for a System Licence to do that.

Use the Google Local Search API

I’ve no idea how the licensing of this works, but calls to the Google Local Search API do correctly geocode full UK postcodes.

A Google spokesman did once say that this might not always be the case, so if you do use this strategy don’t be surprised if it suddenly stops working.

It’s not a good idea to use Google Local Search as a general purpose geocoder. It’s slower than the API geocoder and can sometimes get confused between placenames and business names. So if there’s a possibility that your search string might not be a UK postcode, it’s a good idea to test it first, see below.

Use GDirections

I’ve no idea how the licensing of this works, but calls to GDirections do correctly geocode full UK postcodes. The locations are slightly different from the maps.google.com locations, since they will have been snapped to the nearest street.

The strategy is to request a route from the postcode to itself, like “from: FY2 0HH to: FY2 0HH”, wait for the reply, then use .getPolyline().getVertex(0) to obtain the location.

If you do use this strategy don’t be surprised if it suddenly stops working.

It’s not a good idea to use GDirections as a general purpose geocoder. It’s slower than the API geocoder, has a lower daily quota, and can only handle one request at a time. So if there’s a possibility that your search string might not be a UK postcode, it’s a good idea to test it first, see below.

There’s also considerable doubt about whether this strategy is legal. Read section 10.12 of the Terms for yourself before implementing this strategy.

Testing if a string is a UK postcode

To test if a string looks like a UK post code you can use this regexp
^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$.

That expession assumes that the string is in upper case, has exactly one space between outcode and incode, has no leading or trailing whitespace and no punctuation. That’s a bit more severe than we need, since GDirections and Google Local Search will accept any case and any punctuation and whitespace, so you might want to tidy it up first before performing the test.

That expression should be sufficient to distinguish a full UK postcode from anything else, but if you want to be more exact, there’s a long form in the Wikipedia. Don’t use the very long expression from the Wikipedia article that includes BFPO postcodes, because BFPO postcodes don’t represent fixed geographical locations, but groups of British Overseas Forces which may well be mobile.

Example

Here’s an example that tests whether a search string is a UK postcode, and if so uses the GDirections trick rather than the GClientGeocoder to find the location.

More advanced stuff

Google Maps API Tutorial

Altitude

Google themselves don’t serve altitude information, so if you want to obtain the altitude, you’ll need to get it from somewhere else.

Here’s a simple example

One place where you can get altitude information is the US Geological Survey Elevation Query. Information about their service can be found here:
gisdata.usgs.gov/XMLWebServices/TNM_Elevation_Service.php

A request looks like this:
http://gisdata.usgs.gov/xmlwebservices2/elevation_service.asmx/getElevation?X_Value=-118.4&Y_Value=36.7&Elevation_Units=METERS&Source_Layer=-1&Elevation_Only=true.

The parameters are:

X_Value Longitude
Y_Value Latitude
Elevation_Units METERS or FEET.
Source_layer You can use this to request data from a specific survey, or use -1 to request the best available data at the location.
Elevation_Only true or false. If you set it false you get information about the data source as well as the elevation data.

The service provides a SOAP interface that returns XML, so you can’t access it directly from Javascript for security reasons. What you have to do is to write a little server script that runs in your own domain. Your Javascript can send a request to your own server, which then sends the request to USGS and returns the reply back to your Javascript client.

I’m not a PHP expert, but I managed to throw together something that works for this purpose. A general purpose relay script would need to be more complicated than this, to avoid the possibility of cross-domain attacks, but I think I can trust the USGS. My PHP code looks like this and returns the data like this:altitude.php?lat=53&lng=-2.

There are two asynchronous steps in this chain, so don’t expect to be able to write a function that returns the altitude of a point. Send the request with GDownloadUrl() and then process the reply in the callback funtion. If you’re sending several requests (e.g. to obtain the profile of a cycle route) you can wrap your call in a function and use it to hold Function Closure so that you can match the replies back to the requests.

The service will return up to 10 decimal places of information, but I suspect that the surveys aren’t accurate to 0.1 nanometres. In my code I just use the integer value.

The service returns the value 0 for open sea. You could therefore use it to distinguish land from sea, but there are a few other points on land where the elevation is also zero, e.g. Elburg in the Netherlands.

The documentation states that the service can return the value -1.79769313486231E+308 if there is no valid data for the requested location, so you might want to filter out such values if you’re drawing an elevation diagram.

In this example I use GDirections to find a route, use the EPoly extension to obtain points at equal distances along that route, use USGS to find the altitude at those points, and use the Google Chart API to plot a chart of those altitudes.

More advanced stuff

Google Maps API Tutorial

GLayers

API v2.130 introduces GLayers, which can be used for displaying the Wikipedia and Panoramio layers to your map.

Google themselves don’t (yet) supply a control for allowing users to switch layers on and off, so I wrote this example

IDs and LMCs

The documented way to specify a particular layer is by using its ID. The official list of IDs is atspreadsheets.google.com/pub?key=p9pdwsai2hDN-cAocTLhnag

In addition to the official list, there are also “com.panoramio.popular”, which omits the Panoramio elements that have the small icons, and there’s “com.youtube.all” which displays the YouTube layer, and there are a few other Wikipedia languages. I don’t intend to test all possible Wikipedia languages: If your favourite language is supported by Wikipedia but isn’t in the official GLayers list, try it anyway.

There’s also an undocumented way to specify a particular layer, by using its LMC. E.g.map.addOverlay(new GLayer(“lmc:panoramio/0”)) is the same as map.addOverlay(new GLayer(“com.panoramio.popular”)).

You can only use IDs that the particular release of the main API code knows about, because the main API code needs to know how to translate the ID into an LMC. In v2.130, the known IDs are “com.panoramio.all”, “com.panoramio.popular” and “org.wikipedia.*”.

When you use an LMC, the main API code doesn’t need to translate it for you, so you can use any LMC for which there is a service.

At the moment, the only LMC that I know about that has service but no ID is “lmc:panoramio/1”, which displays the unpopular Panoramio entries and omits the popular ones.

Viewing the source of maps.google.com reveals the existence of “lmc:youtube”, but the API has no service for it at the moment.

hide() and show()

GLayers support .hide(), .show() and .isHidden().

GLayers don’t support .supportsHide().

More advanced stuff

Google Maps API Tutorial

Icon Sprites

This undocumented feature can be used to improve the page loading time in situations where you use several different custom icons.On the left is a single image file that contains ten icon images. GIcon.sprite allows the individual icon images to be cropped out from that image and used as marker icons.Here’s an exampleThe syntax looks like this:

   var myicon = new GIcon();
   myicon.sprite = {image:"sprites.png", width:20, height:34, top:68, left:0}
  • image: the URL of the sprite file. Countermands any existing .image setting.
  • width: the width of the icon. Ignored if the icon already has a .iconSize setting.
  • height: the height of the icon. Ignored if the icon already has a .iconSize setting.
  • top: the vertical pixel position within the sprite file where this icon image starts.
  • left: (optional) the horizontal pixel position within the sprite file where this icon image starts.

It is possible to have sprites of different sizes in the same sprite file.It is possible to use 2D arrays of icon images since v2.141, using “top” and “left” to specify the position.

Thanks to “Esa” for spotting the details of this feature.

More advanced stuff

Google Maps API Tutorial

Using <CANVAS>

It is possible to directly use <canvas> in conjunction with a map.

Here’s an example

Details of how to use <canvas> are available from the Mozilla Developer Centerdeveloper.mozilla.org/en/Canvas_tutorial

However there are a few drawbacks.

Browser Support

Not all browsers support <canvas>, and there is some variation between levels of support in the browsers the do support it. The HTML5 standard which defines <canvas> is still evolving.

In particular, MSIE does not currently support <canvas>.

There is an add on called ExplorerCanvas which can intercept <canvas> canvas commands and convert some of them into VML and Filter commands that MSIE does recognise, but many <canvas> features are not supported, the end result is extremely slow.

Therefore it’s a good idea to test for <canvas> support, and provide some sort of alternative when that support is absent. In the above example, I have a small test canvas which always exists outside the map. If that canvas doesn’t have a .getContext() Method, then I don’t create the active canvas, but create a simple marker instead.

Cryptic error messages

Firefox3 <canvas> error messages are seriously cryptic. They thow a couple of lines of complete gibberish, out of which the only bit that means anything to me is the line number on which the error occurred.

Click handling

<Canvas> elements don’t seem to accept attributes like “onclick” and “onmouseover”, etc.

In some circumstances they seem to eat such events, even in the transparent parts of the <canvas>, preventing them from dropping through to the map controls and overlays below them. In other cirsumstances the clicks do drop through. I don’t know what causes the change in behaviour.

Therefore, if you’re going to use <canvas> in such a way that it overlaps clickable objects, do perform a quick sanity test to see if the clicks are going to reach the underlying elements.

Placing <canvas> elements in a map

You could place your <canvas> elements directly onto one of the map panes, but then you’d have to manage the lat/lng handling yourself.

In the example, I use an ELabel as a container for the <canvas>. This gives the advantage of having all the standard methods like .hide(), .setPoint(), etc. built in.

You could place <canvas> elements inside other structures, such as info windows, or GControls.

You could appendChild a <canvas> element to the map container, but watch out for the click passing problem mentioned above.

<canvas> images and onload function

I don’t usually recommend using onload functions, but if you’re using images in <canvas> then it is necessary to ensure that the image has completely loaded before you attempt to use it in <canvas>. One way to do this is to load the image in the main inline code and launch the <canvas> from the onload event.

Rotating icons

The awkward thing with rotations in <canvas> is that they don’t rotate the object, they rotate the canvas axes around point (0,0), the top left corner of the canvas workspace. That’s not what we generally want. We usually want to rotate an element about its centre.

In other graphics systems, we would translate the object to (0,0), then rotate it, then perform the inverse translation to put it back where it came from.

That’s basically what we have to do in <canvas> but the inverse translation takes place in the rotated frame, so instead of it being (-x,-y) it becomes (x*sin(a)+y*cos(a),y*cos(a)-y*sin(a)). The whole rotate-about-centre operation looks like this:

      var cosa = Math.cos(angle);
      var sina = Math.sin(angle);
      canvas.clearRect(0,0,x*2,y*2);
      canvas.save();
      canvas.rotate(angle);
      canvas.translate(x*sina+y*cosa,x*cosa-y*sina);
      canvas.drawImage(img,-x,-y);
      canvas.restore();

The save() and restore() operations put the axes back where they originally came from.

More advanced stuff

Google Maps API Tutorial

Communicating between iframes

I don’t think it’s possible to pass references to complex Objects, like GMarker()s, between iframes. What you can do instead is to have “helper” functions in the target iframe that accepts simple Objects, like Numbers and Strings, and obtains references to the complex objects within that iframe.

Here’s a simple example

This example has two iframes, one for the map and one for the sidebar.

Only frame1 loads the Google Maps API code.
It loads the XML for the markers in the normal way and adds them to the map. It builds up the sidebar contents in the normal way, but instead of putting them into document.getElementById(“side_bar”), it sends the contents to a helper function in frame2. parent.frame2.sideBar(side_bar_html)

The helper function in frame2 takes the passed string and places in its local “side_bar” div.

Once the side bar has been passed, frame2 contains a series of calls like
<a href=”javascript:parent.frame1.myclick(1)”>. These pass a simple number to the “myclick()” helper function that lives in frame1.

Warning

Debugging Javascript that crosses between iframes is significantly harder than debugging Javascript that operates in a single frame.

More advanced stuff

Google Maps API Tutorial

Using pseudo-HTML data files for maxContent

If you’re using maxContent, or anything else, to display large quantities of HTML data about each marker, then you’ve got to store that data somewhere. If you’ve got lots of markers, things can get messy.

You could store the data in one large XML file or plain text file, but that becomes a pain to create and maintain if you’ve got large amounts of HTML data for each marker.

You could store the maxContent for each marker in a separate HTML file, which you load on demand. The only problem with that is that if you’ve got lots of markers, you end up with lots of files. If you’re using something like googlepages, you have to upload each file, one by one, and there’s a limit of 500 files per googlepages site.

What I came up with is storing the data in one rather unconventional HTML file. The file contains the maxContent HTML for all the markers, using <hr> as a separator. It doesn’t have <head>, <body> or <html> tags or a Doctype, because the maxContent gets injected into a div.innerHTML within an existing page. However, it’s still close enough to acceptable HTML for you to be able to load it into a browser and check the format and content of all the sections at once.

I’ve also put other data about the markers in the same file, separated with “|” characters, but you could just as well store the other data in a separate XML file with the records arranged in the same order.

The data is read in a similar manner to that used when reading a plain text data file, except that the data is split into sections using “<hr>” as the separator, rather than “\n”.

More advanced stuff

Google Maps API Tutorial

GGeoXml with sidebar

GGeoXml doesn’t expose the content that it adds to your map, so you can’t directly obtain information on its markers from Javascript. However, in some circumstances, it is possible to intercept the addoverlay events which are generated when it adds the markers to the map.

Here’s an example

Warning: This trick relies on undocumented details of the GGeoXml behaviour. It may well fail to work in future releases.

Other, more stable, methods for creating a sidebar are EGeoXml and GeoXml

When GGeoXml adds overlays to a map, an “addoverlay” event is triggered. It’s possible to catch that event, extract information about that overlay, and build a sidebar.

This is possible because GGeoXml adds extra accessible properties to the overlays that it creates. These properties currently are:

  • name
  • description
  • snippet
  • hiddenInStream
  • id
  • parentFolderForCallbackOverlayAddTimeout
  • parentGeoXml

The property that we’re interested in for building the sidebar is “name”.

Problems

Overlay management

GGeoXml now performs some sort of crude overlay management on the overlays it creates. This causes the overlays to be removeOverlay()ed when they leave the viewport and addOverlay()ed again when they re-enter the viewport. We need to be careful not to add an extra side bar entry for the overlay each time it re-enters the viewport.

In my example, I add my own extra property to the overlay to remember that I already know about the overlay.

Sidebar order

GGeoXml adds the overlays in random order. If you need the overlays to appear in alphabetical order of name, then you have to sort them yourself.

Long Sidebar

There’s no indication of whether a particular overlay is the last one in the KML file. This means that the usual technique of building the sidebar HTML until the last entry has been processed won’t work. In my example, I add each sidebar entry one by one. If there are large numbers of overlays, this becomes inefficient, since the browser has to re-render the sidebar div after each entry has been added.

I can’t think of any nice way around this, unless you happen to know how many overlays your KML file contains.

Intercepting infowindow content

Another trick that you might want to perform with GGeoXml is to modify the content of the infowindows that it manages. For example you might want to add a “get directions” facility at the bottom, or you might want to have active content in the info window.

It turns out that modifying overlay.description doesn’t modify the contents of the infowindow. The data must be being stored somewhere else before the “addoverlay” event gets triggered.

What you can do is to listen for the undocumented map “infowindowprepareopen” event, and modify the content of the GInfoWindowTab that it passes as a parameter.

In my example I simply add an extra line of text at the bottom of the infowindow contents.

You could place deactivated content in a KML file, perhaps using [ and ] instead of < and >, so that GGeoXml will allow the text to pass through, and then replace those characters as the infowindow opens.

More advanced stuff

Google Maps API Tutorial

Using Cookies

If you want your map to remember its state when the user leaves the page and comes back, then you can write the information into a cookie.

A cookie is a small piece of text that you can ask the user’s browser to store for you so that you can read it back the next time the user visits your page.

You might think that you’d need to write the cookie information every time the map state changes, but in fact you only need to do it when the page exits. Instead of having the onunload=”GUnload()” you can write onunload=”setCookie()” and have your setCookie() function call GUnload() when it has finished.

A cookie can have an expiry time, after which the browser will delete the cookie. A browser with no expiry information is a “session cookie” and will disappear when the current browser session ends.

The cookie is stored by the user’s browser. It is not stored on a server. Each user can have their own stored settings. If the user uses a different browser or a different computer, they will not get the same cookie.

In this example the page will remember the lat, lng, zoom and maptype for seven days.

Although the cookie code doesn’t look too difficult, it seems to have a tendency to be awkward to debug. That’s why I’ve put it in the “Advanced” section of the tutorial.