Embeddable maps

5. Measure Line - Adding the Measuring Control

By default, the embedded map does not have any measuring functionality. To add measuring, we use the available controls from OpenLayers.

http://dev.openlayers.org/docs/files/OpenLayers/Control/Measure-js.html

To add the measuring control use the after init method described below. Replace the script in the JavaScript file with the following:

Copy
function afterInitMethod(eventArgs){        
var measuringControl = new 
OpenLayers.Control.Measure(OpenLayers.Handler.Path, { persist:true, autoActivate:true  } );
measuringControl.events.on( {
                    "measure": measureHandler,
                    "measurepartial": measureHandler
                });
    eventArgs.map.addControl(measuringControl);    
}

function measureHandler(eventArgs){
    var outputSpan = document.getElementById('totalDistance');
    var output = eventArgs.measure.toFixed(3) + ' ' + eventArgs.units;    
    outputSpan.innerHTML = output;
}

Now add this snippet to index.html (after the map placeholder div.)

Copy
<div>            
Total Distance: <span id="totalDistance"></span>
</div>

The code explained

In the example above, two parameters have been added to the constructor for the OpenLayers measure control.

  1. The first is the handler being used (in this case OpenLayers.Handler.Path) which specifies the type of feature that will be drawn for this.

    Note: Other suitable handlers for measurement are OpenLayers.Handler.Polygon or OpenLayers.Handler.RegularPolygon (See also OpenLayers documentation.)

  2. The second parameter is a JSON array of properties accepted by the Measure control. In this case it is specified the control will be active immediately and the drawn lines will persist until the measuring process is triggered again.

Following the initialisation of the measuringControl object, the measureHandler function is bound to the measure and measurepartial events within the control.


function measureHandler(eventArgs){
	var outputSpan = document.getElementById('totalDistance');
	var output = eventArgs.measure.toFixed(3) + ' ' + eventArgs.units;	
	outputSpan.innerHTML = output;
}

The measureHandler function takes the eventArgs from the triggered measuring event, and uses it’s measure and units properties to display the text in the totalDistance span in the html.

<div>		
Total Distance: <span id="totalDistance"></span>
</div>

The div above is used to display the measuring output.

6. Switching between controls