DragZoomControl Examples

Table of Contents

How-To

You can add the DragZoomControl to any Google map with a couple of lines of code.

  1. Include draggzoom.js in your document header.
  2. <script src="dragzoom.js" type="text/javascript"></script>
  3. Add the DragZoomControl to your map like any other control. Example:
  4. map = new GMap2(document.getElementById('map'));
    map.addControl(new GSmallMapControl());
    map.addControl(new DragZoomControl());
  5. Important! Make sure your and doctype and namespaces are set correctly:
  6. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" >
  7. For Internet Explorer: make sure you enable the VML behavior:
    <style type="text/css">v\:* {behavior:url(#default#VML);}</style>

Simple Example

This is the "Hello World" code from the GMaps documentation. The lines you need to add for DragZoom are in bold.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" >
<head>
<style type="text/css">v\:* {behavior:url(#default#VML);}</style>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps JavaScript API Example</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=YOUR_KEY_HERE"
type="text/javascript"></script>
<script src="../src/dragzoom.js" type="text/javascript"></script>
<script type="text/javascript">

//<![CDATA[

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

//]]>
</script>
</head>
<body onload="load()" onunload="GUnload()">
<div id="map" style="width: 900px; height: 600px"></div>
</body>
</html>

View example (simpledragzoom.html).

Enabling the Back Button

The DragZoom Control back button, when enabled, allows the user to return the map to the state it was in prior to the Drag Zoom with a single click. The back button will appear directly under the DragZoom button after the first DragZoom is done and will dissapear after the map has gone back to its original state. Successive DragZooms to increasingly higher zoom levels are supported.

The example uses the "Hello World" code again (but this time moved to the East Coast to provide regional "balance"). Note the one option added to the DragZoom initialization call which enables the back button. When you run this example, do a DragZoom and you will see the back button appear. Do several successive DragZooms and you can back them out in reverse order.

    function load() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById('map'));
        map.setCenter(new GLatLng(40.78, -73.9713), 12);
        map.addControl(new GSmallMapControl());
        map.addControl(new DragZoomControl({}, {backButtonEnabled: true}, {}));
      }
    }

View back button enabled example.

The Back Button and Map Types

The DragZoomControl back button restores the map context as it was prior to the previous DragZoom. The map context not only means the map center and zoom level, but the map type as well. This example illustrates this capability.

The map in the example shows Greater New York. The DragZoom Button is in the top left of the map and the usual Map Type Controls are in the upper right of the map.

Play around, zooming in and out using the DragZoom and changing the Map Type Controls.

View example of restoring Map Types with the back button

Customizing the Options

The DragZoom constructor takes three optional arguments, DragZoomBoxStyleOptions, DragZoomOtherOptions, and DragZoomCallbacks. All three are optional, but if you want to include one, you need to include the previous hashes too, even if they are empty. The following example starts with all the default options but allows you to change any option, style or HTML in the first two arguments that you wish:

Check out this interactive options playground.

Specifying the position of the DragZoomControl button

Like all controls, DragZoomControl can be placed anywhere you want on the map by specifying an optional GControlPosition. (Note this is a map.addControl option, not a DragZoomControl option.)

map.addControl(new DragZoomControl(),new GControlPosition(G_ANCHOR_TOP_RIGHT,new GSize(10,10)));

All the following examples use this option to control the control button(s) position.

Button Styles: making the control buttons look the way you want

The control button default style creates servicable buttons, but you may want to customize them to fit the "look and feel" of your map. This example shows the use of the TextualZoomControl (from the Google Maps API documentation page) and the DragZoomControl with a consistant style. These style definitions go in the second optional parmeter in the DragZoomControl initialization call (see the section above for all the DragZoomControl options):

These are the styles and other parameters used in this example:

        var otherOpts = { 
          buttonStartingStyle: {display:'block',color:'black',background:'white',width:'7em',textAlign:'center',
            fontFamily:'Verdana',fontSize:'12px',fontWeight:'bold',border:'1px solid gray',paddingBottom:'1px',cursor:'pointer'},
          buttonHTML: 'Drag Zoom',
          buttonZoomingHTML: 'Drag a region on the map (click here to reset)',
          buttonZoomingStyle: {background:'yellow'},
          backButtonHTML: 'Drag Zoom Back',  
          backButtonStyle: {display:'none',marginTop:'3px',background:'#FFFFC8'},
          backButtonEnabled: true
        } 
        map.addControl(new DragZoomControl({}, otherOpts, {}), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,39)));

View button styles example.

Using an image for a button instead of text

The next example demonstrates how to substitute an image for text on the DragZoom Control buttons. Basically, you can do so by using the buttonHTML and backButtonHTML and possibbly buttonZoomingHTML arguments (in DragZoomOtherOptions) to specify images rather than text. You can put any valid html in these arguments, even a combination of images and text. Just make sure you set the width and height of the button (through the buttonStartingStyle or the individual button style declarations) as appropriate for the look of the button. If you need the size or background of the button to change when activated, you can set styles in the buttonZoomingStyle argument.

This example uses simple "zoom in" and "zoom out" icons for the DragZoom and back buttons, but uses text for the zooming button. These are the styles and parameters used in this example:

        var otherOpts = { 
          buttonStartingStyle: {background: '#FFF', paddingTop: '4px', paddingLeft: '4px', border:'1px solid black'},
          buttonHTML: '<img title='Drag Zoom In' src='zoomin.gif'>',
          buttonStyle: {width:'25px', height:'23px'},
          buttonZoomingHTML: 'Drag a region on the map (click here to reset)',
          buttonZoomingStyle: {background:'yellow',width:'75px', height:'100%'},
          backButtonHTML: '<img title='Zoom Back Out' src='zoomout.gif'>',  
          backButtonStyle: {display:'none',marginTop:'5px',width:'25px', height:'23px'},
          backButtonEnabled: true, 
          overlayRemoveTime: 1500
        } 
        map.addControl(new DragZoomControl({}, otherOpts, {}), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,15)));

View example using images for the DragZoom and back button.

Advanced: Using Callbacks

This example customizes the overlay (with DragZoomBoxStyleOptions), provides some of the additional options (with DragZoomOtherOptions), and all of the callbacks (with DragZoomCallbacks): see example. The DragZoom instantiation code:

  /* first set of options is for the visual overlay.*/
  var boxStyleOpts = {
    opacity:.2,
    border:"2px solid red"
  }

  /* second set of options is for everything else */
  var otherOpts = {
    buttonHTML:"<img src='zoom-button.gif' />",
    buttonZoomingHTML:"<img src='zoom-button-activated.gif' />",
    buttonStartingStyle:{width:'24px',height:'24px'}
  };

  /* third set of options specifies callbacks */
  var callbacks = {
    buttonclick:function(){display("Looks like you activated DragZoom!")},
    dragstart:function(){display("Started to Drag . . .")},
    dragging:function(x1,y1,x2,y2){display("Dragging, currently x="+x2+",y="+y2)},
    dragend:function(nw,ne,se,sw,nwpx,nepx,sepx,swpx){display("Zoom! NE="+ne+";SW="+sw)}
  };
  
  map.addControl(new DragZoomControl(boxStyleOpts, otherOpts, callbacks));	

View example (advanceddragzoom.html).

Advanced: Combining with Cluster Zoom

Some applications use a zoom mechanisim tailored to the application. The most obvious example is when markers are clustered. Clustering of markers is a way to avoid "clutter" at low zoom levels, and by using a "cluster marker" as a proxy to represent many individual markers which are made visible at higher zoom levels. The Marker Manager is used to control when a particular type of marker is shown. The application may use the cluster markers to bring the user in to the underlying markers it represents by zooming in to the appropriate zoom level and map center when the cluster marker is clicked.

The DragZoomControl back button functionality provides a ready made structure to integrate this type of application zooming methodology with the DragZoom functionality. Two features are used to implement this: a method, (DragZoomMethods: saveMapContext()) and a callback, (DragZoomCallbacks: backbuttonclick). The method is called when the application wants to zoom in to the area of interest (when a cluster marker is clicked). The DragZoom Control then saves the map context on behalf of the application which then does the appropiate zoom and map centering. The method also allows the application to set new text on the back button. When the user subsequently clicks the back button, the map context is restored and an application callback function is called to allow any "clean up" which may be necessary.

In this example, a very simple version of clustering is illustrated: A single cluster marker is placed on the map in Manhattan. Clicking on this cluster marker will cause the map to zoom in to the Central Park area where several markers are displayed for points of interest. When the cluster zoom back button is clicked, the application closes the infoWindow as an example of a clean up. The cluster zoom can be combined with the DragZoom.

This code shows the creation of the map, it's controls and the labels and markers for the example. Remember in order to use the method, the control needs a name:

    function load() {
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById('map'));
        map.setCenter(mapCenter, mapZoom);

        markerMgr = new MarkerManager(map);

        var otherOpts = {
          buttonStartingStyle: {display:'block',color:'black',background:'white',width:'7em',textAlign:'center',
            fontFamily:'Verdana',fontSize:'12px',fontWeight:'bold',border:'1px solid gray',cursor:'pointer'},
          buttonHTML: 'Drag Zoom',
          buttonZoomingHTML: 'Drag a region on the map (click here to reset)',
          buttonZoomingStyle: {background:'yellow'},
          backButtonHTML: 'Drag Zoom Back',  
          backButtonStyle: {display:'none',marginTop:'3px',background:'#FFFFC8'},
          backButtonEnabled: true, 
          overlayRemoveTime: 1500
        } 
        var callbacks = {backbuttonclick:function(method){restoreContextCallback(method)}}
 
        map.addControl(dragZoom = new DragZoomControl({}, otherOpts, callbacks), 
          new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,7)));

        addBoroughLabels();  // Add a label for each borough centered on that borough and load into the Marker Manager
        addParkMarkers();    // Add a marker for the parks near the center of each borough and load into the Marker Manager
        markerMgr.refresh(); // Turn everything on
      }
    }

This shows how the method is invoked:


    // Function to save the map context via the DragZoomControl method and then zoom in to the (lat,lng)
    // called when the cluster marker is clicked
    function saveContextAndZoom(lat,lng,zoom,name) {
      buttonText = name+' Zoom Back';
      dragZoom.saveMapContext(buttonText);
      map.setCenter(new GLatLng(lat,lng),parseInt(zoom));
    }

This shows the callback function:


    // Function called after the map context is restored from the cluster zoom
    // This callback clears the infoWindow if it is open
    function restoreContextCallback(method) {
      if (method) map.closeInfoWindow();      // "method" indicates this particular restore was for 
    }                                         // a zoom called by the method, not the DragZoom button

To see the integration of this scheme with the Drag Zoom Control, bring up the example and do the following:

View example of the integration of application zoom with the DragZoomControl

And here's a real world example:

Browser compatibility

You need a modern browser. DragZoom has been tested with IE6/XP, IE7/XP,Safari2/OS10.4, FF1.4/OS10.4, FF1.4.1/XP, FF2/XP.

It works with Opera9/XP, but there is some jumpiness and odd scrollbar behavior.

Notes