Smashinglabs

Sebastian Poręba's blog

Getting started...

...with gMap is very easy. Simply follow these steps and you're ready to go!

Requirements

To use jquery.gMap simply include jQuery and Google Maps scripts. Using CDN versions sounds like good idea:
			
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.7.1.min.js" type="text/javascript"></script>
			
		

Installation

Download the latest version of gMap and include the Google Maps API along with jQuery and gMap at the page bottom, just before </body> tag (it is good for page loading process).

			
<script src="/scripts/jquery.gmap.min.js" type="text/javascript"></script>
			
		

HTML structure

The HTML structure is quite simple too. Just place a <div> somewhere on your page, style it with CSS (don't forget to assign a fixed width & height) and give it a unique ID or class. If you need a placeholder for browsers not supporting google maps, place any text in div. It will be removed if load succeeds.

			
<div id="map">Placeholder in case of loading failure</div>
			
		

Creating a map

Select the new div element using jQuery's selectors and call the gMap() function on it. I recommend to call the function as soon as the DOM is ready. Please refer to jQuery Events/ready for further infomation.

			
$(window).ready(function () {
$('#map').gMap();
});
			
		

Customizing

gMap can be customized in many different ways. All you need to do is to pass a JSON object to the gMap() function. Please see other tabs for a complete list of properties that can be passed. Options marked red are highly recommended.

Warning! Geocoding (address option) is intended for only few markers and basic setup. Since every marker needs a request, Google allows only limited (probably 10) geocodings. To improve performance always store lat/lng in your database (preferably in numeric(15,12) format).

Main

These are most general options affecting the whole map.

optiontypedefaultsince
logbooleanfalse3.0.0
If you need some info in your javascript console, set it to true. Logs geocoding errors and adding markers and others.
latitudefloat/'fit'0-/3.2.0
Point on which the viewport will be centered. See: centering rules.
Using 'fit' option will calculate center to show all the markers. It may fail combined with address-based markers.
longitudefloat/'fit'0-/3.2.0
Point on which the viewport will be centered. See: centering rules.
Using 'fit' option will calculate center to show all the markers. It may fail combined with address-based markers.
addressstring""1.1.0
Address on which the viewport will be centered. See: centering rules
zoominteger/'fit'3-/3.2.0
Zoom value from 1 to 19 where 19 is the greatest and 1 the smallest.
Using 'fit' option will calculate zoom to show all the markers. It may fail combined with address-based markers.
minZoominteger-3.2.0
Min allowed zoom value
maxZoominteger-3.2.0
Max allowed zoom value
maptype-google.maps.MapTypeId.ROADMAPchanged in 3.0.0
Predefined variable for setting the map type. Please refer to the
Google Maps API for possible values.

Controls

optiontypedefaultsince
mapTypeControlbooleantrue3.0.0
The MapType control lets the user toggle between map types (such as ROADMAP and SATELLITE).
Please refer to Google Maps API for more information.
zoomControlbooleantrue3.0.0
The Zoom control displays a slider (for large maps) or small "+/-" buttons (for small maps) to control the zoom level of the map.
Please refer to Google Maps API for more information.
panControlbooleanfalse3.0.0
The pan control displays buttons for panning the map.
Please refer to Google Maps API for more information.
scaleControlbooleanfalse3.0.0
The scale control displays a map scale element.
Please refer to Google Maps API for more information.
streetViewControlbooleantrue3.0.0
The Street View control contains a Pegman icon which can be dragged onto the map to enable Street View.
Please refer to Google Maps API for more information.
controlsPositionsobject{}3.3.2
Positions of 5 default controls. Possible values are:
  • google.maps.ControlPosition.TOP_CENTER/li>
  • google.maps.ControlPosition.TOP_LEFT
  • google.maps.ControlPosition.TOP_RIGHT
  • google.maps.ControlPosition.LEFT_TOP
  • google.maps.ControlPosition.RIGHT_TOP
  • google.maps.ControlPosition.LEFT_CENTER
  • google.maps.ControlPosition.RIGHT_CENTER
  • google.maps.ControlPosition.LEFT_BOTTOM
  • google.maps.ControlPosition.RIGHT_BOTTOM
  • google.maps.ControlPosition.BOTTOM_CENTER
  • google.maps.ControlPosition.BOTTOM_LEFT
  • google.maps.ControlPosition.BOTTOM_RIGHT
as described in Google Maps API
mapType-null3.3.2
zoom-null3.3.2
pan-null3.3.2
scale-null3.3.2
streetView-null3.3.2
controlsStyleobject{}3.3.2
Special style of control. Described in Google Maps API.
mapType-google.maps.MapTypeControlStyle.DEFAULT3.3.2
Possible values:
  • google.maps.MapTypeControlStyle.HORIZONTAL_BAR displays the array of controls as buttons in a horizontal bar as is shown on Google Maps.
  • google.maps.MapTypeControlStyle.DROPDOWN_MENU displays a single button control allowing you to select the map type via a dropdown menu.
  • google.maps.MapTypeControlStyle.DEFAULT displays the "default" behavior, which depends on screen size and may change in future versions of the API
zoom-google.maps.ZoomControlStyle.DEFAULT3.3.2
Possible values:
  • google.maps.ZoomControlStyle.SMALL displays a mini-zoom control, consisting of only + and - buttons. This style is appropriate for small maps. On touch devices, this control displays as + and - buttons that are responsive to touch events.
  • google.maps.ZoomControlStyle.LARGE displays the standard zoom slider control. On touch devices, this control displays as + and - buttons that are responsive to touch events.
  • google.maps.ZoomControlStyle.DEFAULT picks an appropriate zoom control based on the map's size and the device on which the map is running.
controlsarray[]changed in 3.0.0
List of additional controls on the map. Actually you shouldn't use it if you don't have to. It's not related to V2 controls array and is intended for advanced users only. Use above 5 booleans to set standard controls.
pos-null3.0.0
Google Maps API position constant, f.e. google.maps.ControlPosition.BOTTOM_CENTER. Please refer to Google Maps API for more information.
divDOM Objectnull3.0.0
Object to push as a control. You should set all CSS and actions on created element before.
scrollwheelbooleantrue-
Set to false to disable zooming with your mouses scrollwheel.

Route finder

optiontypedefaultsince
routeFinderobject3.3.0
travelModestring"BYCAR"3.3.0
Travel mode, possible values: "BYCAR", "BYBICYCLE", "BYFOOT"
travelUnitstring"KM"3.3.0
Travel units, possible values: "MILES", "KM"
routeDisplayjQuery objectNULL3.3.0
Default element for route finder
routeErrors{}3.3.0
INVALID_REQUESTstringThe provided request is invalid.3.3.0
NOT_FOUNDstringOne or more of the given addresses could not be found.3.3.0
OVER_QUERY_LIMITstringA temporary error occured. Please try again in a few minutes.3.3.0
REQUEST_DENIEDstringAn error occured. Please contact us.3.3.0
UNKNOWN_ERRORstringAn unknown error occured. Please try again.3.3.0
ZERO_RESULTSstringNo route could be found within the given addresses.3.3.0

Warning! Geocoding (address option) is intended for only few markers and basic setup. Since every marker needs a request, Google allows only limited (probably 10) geocodings. To improve performance always store lat/lng in your database (preferably in numeric(15,12) format).

Marker specific

optiontypedefaultsince
markersarray[]-
List of points to be marked on the map. Every entry in this array has to be in object. If at least one entry is given the viewport will be centered to the first point/address. Every entry contains the following properties:
addressstring""1.1.0
Address where the marker will be drawn.
latitudefloat0-
Point on the map where the marker will be drawn
longitudefloat0-
Point on the map where the marker will be drawn
keystring03.2.0
Key that can be used with getMarker function
htmlstring""-/1.1.0
Content that will be shown within the info window for this marker. If empty no info window will be shown when the user clicks the marker.
Since 1.1.0 you can set the value to _address or _latlng to display the respective values of the current marker.
titlestring""3.0.1
String displayed over marker on hover. You can set the value to _address or _latlng to display the respective values of the current marker.
popupbooleanfalse-
If true the info window for this marker will be shown when the map finished loading. If "html" is empty this option will be ignored.
iconjson{}1.0.2
Subset of properties for defining a custom image for the current marker. Please see the global "icon" property below for a list of options.

Global

optiontypedefaultsince
html_prependstring<div class="gmap_marker">1.0.1
HTML string to get prepended to a marker's info window. Useful for styling through CSS.
html_appendstring<div class="gmap_marker">1.0.1
HTML string to get appended to a marker's info window.
iconjson--
Subset of properties for defining a custom marker image for all markers.
imagestringhttp://www.google.com/mapfiles/marker.png-
Full path to a image that indicates the marker on the map.
shadowstringhttp://www.google.com/mapfiles/shadow50.pnggfixed in 3.1.0
Full path to a image that indicates the shadow for the marker image on a map. This property is optional (e.g. your image already includes a drop shadow).
iconsizearray[20, 34]-
A simple array of integer values for width and height valid for "image".
shadowsizearray[37, 34]fixed in 3.1.0
Same as above, only for "shadow".
iconanchorarray[9, 34]-
The pixel coordinate relative to the top left corner of the icon image at which this icon is anchored to the map.
infowindowanchorarray[9, 2]-
The pixel coordinate relative to the top left corner of the icon image at which the info window is anchored to this icon.
singleInfoWindowbooleantrue3.1.0
This setting forces only one infowindow open at the time. It's enabled by default, to correspond with default (and only) setting in V2 API.

Callbacks

optiontypedefaultsince
onCompletefunctionfunction(){}3.1.0
Function called after loading of all markers. It's useful while using geocoding, when you have to wait for all requests to complete.

Additional functions

Additional functions may be called on gMap enabled element. Use syntax:

                  
 $("#map").gmap("function name", argument1, argument2, ...); 
                  
                
using any function name given below. Examples were provided with possible arguments and ideas for usage.

optionargumentssince
addMarkermarker configuration3.2.0
                  
// you may pass even more complex marker
 $("#map").gmap("addMarker", {latitude: 50.083, longitude: 19.917}); 
                  
                
addMarkersmarker configuration array3.2.0
Shorthand for multiple markers adding.
                  
 $("#map").gmap("addMarkers", [{latitude: 50.083, longitude: 19.917}, {latitude: 50.283, longitude: 19.717}]); 
                  
                
removeAllMarkersnone3.2.0
                  
$("#map").gmap("removeAllMarkers");
                  
                
getMarkermarker key3.2.0
                  
$("#map").gMap('getMarker', 'key5');
                  
                
fixAfterResizeboolean3.3.0
To make life easier, there is a new function fixing all issues described in examples. Call $('#map').gMap('fixAfterResize'); or $('#map').gMap('fixAfterResize', true); to fix resized map. Optional flag (true) enables ugly hack for rapid centering instead of default, smooth one.
                  
$("#map").gMap('fixAfterResize', true);
                  
                
setZoomzoomlevel3.3.0
                  
map.gMap('setZoom',"fit");
                  
                
changeSettingsconfig object3.3.0
Designed to let you change any map settings. Currently tested with: latitude, longitude, zoom.
                  
map.gMap('changeSettings', {
	latitude: 50.20917,
	longitude: 19.75435,
	zoom: 'fit'
});
                  
                
mapclickcallback3.3.0
Callback will be called if user clicks on map. LatLng object will be passed as an argument.
                  
map.gMap('mapclick',function(latlng){console.log(latlng);});
                  
                
geocodeaddress, callback3.3.0
Geocodes given address and calls a callback with latlng as an argument. Extremaly useful if you need to turn your address coded database into lat/lng coordinates.
                  
map.gMap('geocode',"Kraków, Poland", function(latlng){console.log(latlng);});
                  
                
getRouteobject with options: {to, from, routeDisplay}3.3.0
Takes two lat/lng and calculates route, shows steps in routeDisplay element. Uses configuration object routeFinder.
                  
var data = $('#map').data('gmap');
$("#map").gMap("getRoute", {from: data.markers[0].getPosition(), to: data.markers[1].getPosition(), routeDisplay: $("#routeDisplay")});
                  
                

Handling gmap after initialisation

I understand that this plugin is best for initial displaying of markers and stuff. If you want to manipulate map later by yourself, simply call:

			  
var gmap = $("#map").data("gmap");

gmap === {
	'opts': opts, // plugin options, used internally
	'gmap': $gmap, // google map object
	'markers': [], // array of markers
	'infoWindow': null // currently opened infowindow
};
			  
			
Note: in 3.0.0 it was $("#map").data("$gmap"); and returned only map object. I found it less extensible and now it's returning object. However, for backward compatibility, if you call data("$gmap") you will get map object as in older version. This behaviour may be removed later.

Map centering rules

In 3.0.0 map is centered based on following points:

  • address in options
  • latitude & longitude in options
  • address of marker[0]
  • latitude & longitude of marker[0]
  • failsafe (0,0)
With 3.1.0 it has changed to:
  • latitude & longitude in options
  • address in options
  • latitude & longitude of first marker having it
  • address of first marker
  • failsafe (0,0)
Reason of such change is mess caused by geocoding. To find center with given address gMap must initialise map, set center to some random point, then call geocoding and use callback with setCenter to set center again. It causes loading speed dropdown, so please provide map center latitude&longitude always when possible.

API V2

Google Maps API V2 is no longer supported in 3.0.0 version. Following documentation is for V3 version only. If you need V2 docs please visit http://gmap.nurtext.de/documentation.html.
If you need migration help please visit guide.

  • RSS
  • Facebook
  • Twitter

FAQ about Wordpress

If you are a template developer: I don't mind anyone using ...

gMap 3.3.3 released

In the late evening an international number called my mobile. ...

Talks for Google Dev

First one from Google I/O Extended event in Krakow, about ...

Talks and lectures w

Bret Victor - Inventing on Principle Very inspiring talk about tools ...

3D Tetris with Three

[include file="ThreejsTetrisMenu.php"] Completed slices and score counting This function will be quite ...

FAQ about Wordpress

If you are a template developer: I don't mind anyone using ...

gMap 3.3.0 released

As always, you can download it from github. I had a ...

Lecture for GTUG: Ja

My main topics were: Optimization in general DOM Reflow/repaint Garbage collector JIT Google Closure (Compiler/Tools/Library) You can ...

Unit testing for jQu

In part 1 I described basics of unit testing in ...

Unit testing for jQu

There are few testing frameworks dedicated for frontend that are ...