Web Maps Lite API Examples

Basic Events

Its been an eventful day

Javascript Level: Intermediate

So far we've looked at how to put stuff onto maps. But what if you want to get information from the map? Maybe you want visitors to your site to be able to click on a point so you can store the point's location or show the location to the user. When you click or drag the map below you can see the latitude and longitude at the bottom changing:

Drag or click the map.

Here's the JavaScript for the example:

var cloudmade = new CM.Tiles.CloudMade.Web({key: 'BC9A493B41014CAABB98F0471D759707'});
var map = new CM.Map('cm-example', cloudmade);
  
map.setCenter(new CM.LatLng(-33.8609,151.2112), 13);
    
function displayMessage(msg) {
	document.getElementById('message').innerHTML = msg;
}
    
CM.Event.addListener(map, 'click', function(latlng) {
	displayMessage("You have clicked the map at " + latlng.toString(4));
});
    
CM.Event.addListener(map, 'dragend', function() {
	displayMessage("You have dragged the map to " + map.getCenter().toString(4));
});

Ok, thats a lot of Javascript, lets look at it one bit at a time.

1. First we create a CloudMade map in the usual way:

var cloudmade = new CM.Tiles.CloudMade.Web({key: 'BC9A493B41014CAABB98F0471D759707'});
var map = new CM.Map('cm-example', cloudmade);		
map.setCenter(new CM.LatLng(-33.8609,151.2112), 13);

2. Now we'll write a little helper function that displays a message in a div element with the id "message":

function displayMessage(msg) {
	document.getElementById('message').innerHTML = msg;
}

Lets put this div element into the body of the document, in this case - near our "cm-example" div where the map resides:

<div id="message">Drag or click the map.</div>

3. Now we use the CM.Event.addListener function, passing it the "map" object, the type of event (in this case a "click" event) and the function that will be called when the event fires. The function accepts "latlng" argument which will hold the latitude and longitude generated by the click event. Inside our listener function we use our displayMessage function from Step 2 to display the latitude and longitude generated by a click, passing it the "latlng" variable converted to a string and limited to 4 decimal places.

CM.Event.addListener(map, 'click', function(latlng) {
	displayMessage("You have clicked the map at " + latlng.toString(4));
});

4. Next we add a similar event listener, that responds to a dragging event. This time we use our "displayMessage" function along with the "getCenter" function to display the latitude and longitude of the map after it has been dragged.

CM.Event.addListener(map, 'dragend', function() {
	displayMessage("You have dragged the map to " + map.getCenter().toString(4));
});

To find out more about event handlers, take a look at our documentation. You can also take a look at the list of events available for the CM.Map object.

Now lets go to the next example - Info Window.