Google Maps Guidelines

From Fishcakes Wiki

Jump to: navigation, search
Edit Menu

Image:Icon_Google_Maps_40px.png Google Maps Guidelines

This page contains a guide to the Google Maps API including setting up a map page and basic explanation of variables.

If you want a detailed guide visit Google Maps API Documentation which guides you through the concepts and includes code examples.


Contents

Setup the HTML File

Initialise Google Maps API

Initialise Google Maps API key in HTML Header of document and load Javascript file:

<script src="http://maps.google.com/maps?file=api&v=1&key=YOUR_API_KEY" type="text/javascript"></script>
<script src="javascript_file.js" type="text/javascript"></script>

Create HTML DIV for Map

Create a DIV in HTML page with id="map" Javascript node to load the map into:

<div id="map" style="width: 500px; height: 500px"></div>

Display a Google Map with Javascript

This is the basic code for loading a map.

function load() {
   if (GBrowserIsCompatible()) {
      var map = new GMap2(document.getElementById("map"));
      map.setCenter(new GLatLng(37.4419, -122.1419), 13);
   }
}

Map Variables

These variables check browser compatibility and initialise the map.

  • GBrowserIsCompatible — checks if browser compatible.
  • var map — creates variable 'map' to load into the HTML div.
  • GMap2 — initialises an instance of a Map using version 2 of the API. You can have GMap but this will call the old version of the API.

GPoints

These variables are part of the GPoints which calls the map position and zoom level.

  • (new GLatLng(37.4419, -122.1419), 13) — set latitude and longitude and zoom level.
  • GLatLng(lat,lon) — set latitude and longitude for map centre.
  • setCenter((),X) — centres map on page with zoom level X.

Note: Zoom levels run from 15 (closest) to 1 (whole earth). USA has all zoom levels, other regions only guaranteed to level 6. Zoom levels levels 16-18 show different types of wrapping.

GMapType Set Map Type

If you leave this code out, then the standard street map will be displayed.

map.setMapType(G_SATELLITE_MAP );
  • setMapType — calls the set map function.
  • G_NORMAL_MAP — normal street map.
  • G_SATELLITE_MAP — satellite images.
  • G_HYBRID_MAP — transparent street maps over satellite images.

You can also define your own GMapType and display a special map, or even another image you want to map points on. Need to research this one...

  • G_DEFAULT_MAP_TYPES — array of all three predefined map types described above.
  • GMapType() — calls the map

Map Control Widgets

You can add a map controller using the addControl() function.

map.addControl(new GLargeMapControl());

Zoom Controller

  • GLargeMapControl — large pan/zoom controller with pan arrows (N,S,E,W & Center) and zoom +/- with zoom slider.
image:GLargeMapControl.png
  • GSmallMapControl — mini pan/zoom controller with pan (N,S,E,W) and zoom +/-.
image:GSmallMapControl.png
  • GSmallZoomControl — basic zoom controller with zoom +/-.
image:GSmallZoomControl.png

Map Type Controller

  • GMapTypeControl — add a toggle between Map, Satellite or Hybrid controller.
image:GMapTypeControl.png

Map Scale Controller

  • GScaleControl — add a metric/imperial scale added to bottom-left of map.
image:GScaleControl.png


Location Markers

Location markers allow you to map points onto your page with a location marker icon display. You'll probably want to start with the centre point of your map. Image:Google_Maps_Marker.png

var myMarker = new GMarker(new GPoint(37.4419, -122.1419));
map.addOverlay(myMarker);
  • GMarker — create a new marker.
  • GPoint(lat,lon) — position the marker on the map.
  • addOverlay() — adds the marker to the map.

Example Code

Source code for externalising the above functions and allowing multiple markers loaded via an XML file.

//<![CDATA[
 
var centerLatitude = 40.6897;
var centerLongitude = -95.0446;
var startZoom = 3;
var map;
 
var markers = [
   {
      'latitude': 37.818361,
      'longitude': -122.478032,
      'name': 'Golden Gate Bridge'
   },
   {
      'latitude': 40.6897,
      'longitude': -74.0446,
      'name': 'Statue of Liberty'
   },
   {
      'latitude': 38.889166,
      'longitude': -77.035307,
      'name': 'Washington Monument'
   }
];
 
function addMarker(latitude, longitude, description) {
   var marker = new GMarker(new GLatLng(latitude, longitude));
 
   GEvent.addListener(marker, 'click',
      function() {
         marker.openInfoWindowHtml(description);
      }
   );
   map.addOverlay(marker);
}
 
function load() {
   if (GBrowserIsCompatible()) {   
      map = new GMap2(document.getElementById("map"));
      map.addControl(new GSmallMapControl());
      map.addControl(new GMapTypeControl());
      var location = new GLatLng(centerLatitude, centerLongitude);
      map.setCenter(location, startZoom);
 
      for(id in markers) {
         addMarker(markers[id].latitude, markers[id].longitude, markers[id].name);
      }
 
   }
}
 
window.onload = init;
window.onunload = GUnload;
 
//]]>

Catching User Interaction

Creating a map with display markers which have info windows added by user clicks.

Markers

  • GMap2.openInfoWindow() — create new markers and info windows on map.
  • GMarker.openInfoWindow() — display existing markers and info windows on map.
  • GIcon() — customise map pin icon.
  • GIcon.image — url of image
  • GIcon.iconSize — image size in pixels
  • GIcon.iconAnchor — location
  • GIcon.infoWindowAnchor — info window location



Example Code

see Javascript Code reference file below...

NOTE: These files are linked to dansalmon.dyndns.org. Need to move to wiki.fishcakesmedia.com/adev/...

Listening for User Interaction

GEvent.addListner

This event handler watches for user interaction and triggers events. Here's a simple script to listen for user click to create a marker:

GEvent.addListener(map, "click", function(overlay, latlng) {
   var marker = new GMarker(latlng)
   map.addOverlay(marker);
});

openInfoWindow()

Overlays an info window on a map.

GEvent.addListener(map, "click", function(overlay, latlng) {
   map.openInfoWindow (latlng,document.createTextNode("You Clicked Here"));
});

GXmlHttp

Saves data gathered from user interaction.

Zoom level jumps

Zoom level jumps are caused by using a string variable when setting the zoom level. When reading zoom level value from a database, or from an input field on your page, you need to convert them to an integer with parseInt(zoom) function. Similarly, x/y and latitude/longitude values should be converted to numbers using parseFloat(value).

To parse a value from a MySQL database, use:

var startZoom = parseInt({$googlemap->map_zoom});
var centerLatitude = parseFloat({$googlemap->map_lat});
var centerLongitude = parseFloat({$googlemap->map_lon});

Google Maps Notes

Zooming in of the satellite images is possible, as it is for the maps, though not all areas have images available in all resolutions. Of the 15 zoom levels, its possible to view the whole world down 6 levels, below which the system states "We're sorry but we don't have imagery at this zoom level for this region. Try zooming out for a broader look". Mexico and the Northern reaches of Canada can zoom in 12 levels, whilst the USA is covered down all 15 zoom levels as far as I can tell. At the same zoom level, the maps and satellite images are not an exact overlay of the same area.

Image:Google-zoom-levels.png

API Reference

Map Setup

  • var map = new GMap2();
  • var size = new GSize(50, 50);
  • var bounds = new GLatLngBounds(new GLatLng(-34, 151), new GLatLng(-33, 152));
  • var latlng = new GLatLng(-33.8716, 151.203493);
  • var latlng2 = new GLatLng(22.283378, 114.150181);
  • var marker = new GMarker(latlng);
  • var div1 = document.createElement('DIV');
  • div1.innerHTML = '<h3>An info window=</h3>' — Supports most html and css. Content restricted to approx 4kb.
  • var div2 = document.createElement('DIV');
  • div2.innerHTML = '<h4>An info window tab</h4>';
  • var tab1 = new GInfoWindowTab('First tab', div1);
  • var tab2 = new GInfoWindowTab('Second tab', div2);
  • var tab1html = new GInfoWindowTab('First tab', div1.innerHTML);
  • var tab2html = new GInfoWindowTab('Second tab', div2.innerHTML);
  • function jitter() { return 0.1 * (Math.random() - 0.5); }
  • function makePoint() { return new GLatLng(latlng.lat() + jitter(), latlng.lng() + jitter()); }
  • function openPoints(n) { var points = []; while (n--) points.push(makePoint()); return points; }
  • function closedPoints(n) { var points = openPoints(n); points.push(points[0]); return points; }
  • var polyline = new GPolyline(openPoints(3), '#8888FF', 10, 0.5);
  • var polygon = new GPolygon(closedPoints(3), '#000000', 2, 1.0, '#88FF88', 0.25);
  • var geocoder = new GClientGeocoder();

Display Controls

  • map.draggingEnabledAsync( function(x) {alert(x);} ) — display whether the map is draggable
  • map.infoWindowEnabledAsync( function(x) {alert(x);} ) — display whether info windows are enabled
  • map.doubleClickZoomEnabledAsync( function(x) {alert(x);} ) — display whether double click to zoom is enabled
  • map.continuousZoomEnabledAsync( function(x) {alert(x);} ) — display whether continuous smooth zooming is enabled
  • map.getMapTypesAsync( function(x) {alert(x);} ) — display the array of map types
  • map.getCurrentMapTypeAsync( function(x) {x.getNameAsync(function(y) {alert(y);});} ) — display the currently selected map type
  • map.setMapType(G_NORMAL_MAP) — switch to map mode
  • map.setMapType(G_SATELLITE_MAP) — switch to satellite mode
  • map.setMapType(G_HYBRID_MAP) — switch to hybrid mode
  • map.isLoadedAsync( function(x) {alert(x);} ) — display whether the map is loaded
  • map.getCenterAsync( function(x) {alert(x.lat() + ',' + x.lng())} ) — display the coordinates of the map's center
  • map.getBoundsAsync( function(x) {sw = x.getSouthWest(); ne = x.getNorthEast(); alert('SW: ' + sw.lat() + ',' + sw.lng() + 'NE: ' + ne.lat() + ',' + ne.lng())} ) — display the coordinates of the Southwest and Northeast corners of the map
  • map.getBoundsZoomLevelAsync(bounds, function(zoom) {alert(zoom)}) — gets the zoom level required to display the given bounds
  • map.getSizeAsync( function(x) {alert(x.toString())} ) — display the size of the map view in pixels
  • map.getZoomAsync( function(x) {alert(x)} ) — display the current zoom level
  • map.setCenter(latlng) — center the map on the Google Sydney office
  • map.setCenter(latlng, 15) — center the map on the Google Sydney office and go to zoom level 15
  • map.setCenter(latlng, 15, G_SATELLITE_MAP) — center the map on the Google Sydney office, go to zoom level 15, and switch to Satellite mode
  • map.panTo(latlng) — pan to the Google Sydney office
  • map.panBy(size) — pan the map a given number of pixels
  • map.panDirection(-1, -1) — pan the map in the given direction proportionally to the current viewport size
  • map.setZoom(2) — go to zoom level 2 (far out)
  • map.zoomIn() — zoom in one level
  • map.zoomOut() — zoom out one level
  • map.addOverlay(marker) — add a marker to the map
  • map.addOverlay(polyline) — add a polyline to the map
  • map.addOverlay(polygon) — add a polygon to the map
  • map.removeOverlay(marker) — remove the marker from the map
  • map.clearOverlays() — clear all overlays for this mapplet
  • map.openInfoWindow(latlng, div1) — open an info window with a html element.
  • map.openInfoWindowHtml(latlng, 'A html string') — open an info window with a html string.
  • map.openInfoWindowTabs(latlng, [tab1, tab2]) — open a tabbed info window
  • map.openInfoWindowTabsHtml(latlng, [tab1html, tab2html]) — open a tabbed info window with html strings
  • map.getInfoWindowAsync(function(infoWindow){alert(infoWindow);}) — close the info window.
  • map.closeInfoWindow() — close the info window.
  • map.showMapBlowup(latlng) — show a blowup of the map.

Overlay Controls

  • map.addOverlay(marker) — add a marker to the map
  • marker.openInfoWindow(div1) — open an info window with a html element.
  • marker.openInfoWindowHtml('A html string') — open an info window with a html string.
  • marker.openInfoWindowTabs([tab1, tab2]) — open a tabbed info window
  • marker.openInfoWindowTabsHtml([tab1html, tab2html]) — open a tabbed info window with html strings
  • marker.getPointAsync(function(aLatlng) {alert(aLatlng)}) — get the center point of the marker.
  • marker.setPoint(Math.random() > 0.5 ? latlng : latlng2) — set the center point of the marker.
  • marker.getIconAsync(function(icon) {alert(icon.image)}) — retrieve the icon for a marker.
  • marker.draggingAsync(function(dragging) {alert(dragging)}) — query a marker to see if it is currently dragging.
  • marker.draggableAsync(function(draggable) {alert(draggable)}) — query a marker to see if it is draggable.
  • map.addOverlay(polyline) — add a polyline to the map
  • polyline.getVertexCountAsync(function(count) {alert(count);}) — get the number of vertices in the polyline.
  • polyline.getVertexAsync(0, function(vertex) {alert(vertex);}) — get a polyline vertex.
  • map.addOverlay(polygon) — add a polygon to the map
  • polygon.getVertexCountAsync(function(count) {alert(count);}) — get the number of vertices in the polygon.
  • polygon.getVertexAsync(0, function(vertex) {alert(vertex);}) — get a polygon vertex.
  • geocoder.getLatLngAsync('Brandschenkestrasse 110, Zurich', function(latlng) {map.setCenter(latlng)}); — geocode an address
  • geocoder.getLocationsAsync('Brandschenkestrasse 110, Zurich', function(json) {alert(tosource(json))}) — detailed geocoder response.

Unsupported Controls

  • map.enableDragging() — not supported
  • map.disableDragging() — not supported
  • map.enableInfoWindow() — not supported
  • map.disableInfoWindow() — not supported
  • map.enableDoubleClickZoom() — not supported
  • map.disableDoubleClickZoom() — not supported
  • map.enableContinuousZoom() — not supported
  • map.disableContinuousZoom() — not supported
  • map.addControl(someControl) — not supported
  • map.removeControl(someControl) — not supported
  • map.getContainer() — not supported
  • map.savePosition() — not supported
  • map.returnToSavedPosition() — not supported
  • map.checkResize() — not supported
  • map.addMapType(someType) — not supported
  • map.removeMapType(someType) — not supported
  • map.getPane() — not supported

Google Map Parameters URL Codes

A list of parameters that can be passed to maps.google.com. You might want to pass such parameters if you want to get Google Maps to display driving directions, which are not available under the API.

  • q= Query - anything passed in the q parameter is treated as if it had been typed into the query box on the maps.google.com page.
  • ll= Latitude,longitude of map centre - Note the order. Only decimal format is accepted. If this is used without a query, then the map is centred at the point but no marker or info window is displayed
  • sll= Latitude,longitude of the point from which the business search should be performed. You could use this to perform an off-centre busness search. Google use it so "link to this page" can record a map that has had the centre moved after performing a business search.
  • spn= Approximate lat/long span. The zoom level will be adjusted to fit if there's no &z parameter. Use this Mapki tool to find a lat and long.
  • sspn= ?? lat/long of... what?
  • hl= Host language - only a few languages are supported, e.g. &hl=fr for French.
  • t= Map Type. The available options are "t=m" map, "t=k" satellite, "t=h" hybrid
  • saddr= Source address. Use this when asking for driving directions. Any text added in brackets is displayed in the sidebar in bold
  • daddr= Destination address(es). Use this when asking for driving directions. Any text added in brackets is displayed in the sidebar in bold. Also "+to:" clauses can be appended to the destination to request multiple destination routing, like this "&dadr=Blackpool+to:Manchester+to:Leeds" text in brackets can also be added to the "+to:" clauses.
  • mrad= Additional destination address. If you've got three points in your trip you can use &saddr, &daddr and &mrad instead of "+to:" clauses.
  • start= Skips the first (start-1) matches
  • num= Display, at most, this number of matches. The valid range is 0 to 10 (but 0 is a bit pointless).
  • near= Can be used as the location part of a query instead of putting the whole thing into &q.
  • f= Controls the style of query form to be displayed. &f=d displays the "directions" form (two input boxes: from, to), &f=l displays the "local" form (two input boxes: what, where). Otherwise the default search form is displayed (single input).
  • output=html Uses the old style Google Local page format from before it merged with Google Maps, with the small map and large sidebar.
  • output=js Outputs JavaScript object literals and function calls used by Google Maps, including encoded polyline data for driving directions, and stage information in HTML format.
  • output=kml Outputs a KML file containing full Placemark information representing the current map.
  • output=nl Outputs a small KML file containing a NetworkLink wrapper linking to a URL from which Google Earth and Google Maps can obtain the Placemark information.
  • latlng= This is a weird one. It takes three numbers separated by commas. The first two numbers (presumably representing latitude and longitude multiplied by 1000000) are ignored. The third number seems to be a Google internal "Company ID" number for a particular business. E.g. &latlng=0,0,14944637421527611642 represents Blackpool Community Church. Specifying this parameter performs a Google Search for pages that reference that business, and displays a tiny map. Other parameters, in particular &q, must have valid contents (but need not relate to the target business) for this to work.
  • cid= Similar to latlng, but generating a different map size. It takes three numbers separated by commas. The first two numbers (presumably representing latitude and longitude multiplied by 1000000) are ignored. The third number seems to be a Google internal "Company ID" number for a particular business. E.g. &cid=0,0,14944637421527611642 represents Blackpool Community Church. Specifying this parameter displays a large map of the identified company location. Other parameters, in particular &q, must have valid contents (but need not relate to the target business) for this to work.
  • vp= The presence of this parameter causes maps.google.com to switch into Copyright Service mode. Instead of returning the html that draws a map, it returns information about the copyright ownership in Javascript format. The &vp parameter specifies the viewpoint (i.e. the centre of the map). Copyright Service only works when the &spn and &z parameters are also supplied, indicating the span and the zoom. Optional parameters are &t, which specifies the map type, and &key which specifies the API key of the site performing the request. E.g. maps.google.com/maps?spn=0.030372,0.068665&z=6&t=h&vp=53.859462,-3.038235
  • om= The presence of this parameter with a value other than 1 causes the overview map to be closed. If the parameter is omitted, or present with the value 1, then the overview map is open.
  • ie= Can be used to specify the character set. e.g. &ie=UTF8.
  • pw= Activates print mode and initiates printing. There seems to be a problem at the moment with &pw=1, but using settings like &pw=2 is OK.
  • z= Sets the zoom level.
  • iwloc= Specifies where the infowindow will be displayed. In a business search &iwloc=A to &iwloc=J will open the info window over the corresponding business marker, and &iwloc=near will place it over the big green arrow if that's currently displayed. &iwloc=addr can be used on map search to explicitly request the info window to be open on the address, but that's the default anyway. Directions search supports &iwloc=start, &iwloc=end and &iwloc=pause1 etc.
  • layer=t Activates the traffic overlay
  • msa=b Activates the "My Maps" sidebar when used in conjunction with "maps.google.com/ms". It does nothing without the "/ms" and "/ms" does nothing without the "&msa=b".
  • msa=0 Involved in My Maps processing. Possibly specifies the My Maps server number.
  • msid= Specifies a My Maps identifier. When used in conjunction with "maps.google.com/ms" and &msa=0, the corresponding My Map is displayed.
  • mrt=kmlkmz Skips the normal search and goes directly to User-Created Content. Only works if the query contains a location and something to search for. E.g. q=hotel&near=london&mrt=kmlkmz or q=hotel+in+london&mrt=kmlkmz.
  • view= Can be used to select text view (view=text) or the normal map view (view=map)
  • dirflg=h Switches on "Avoid Highways" route finding mode.


Links for this Page

Image:Icon Resources 20px.png Google Maps Links

Official Google Maps Links

Unofficial Google Maps Links

Great Google Maps Sites

Other Google Applications

  • Google Trends — compare the world's interest in your favourite topics.


Personal tools