OpenLayers Tutorial – Place a Marker

March 27th, 2011

This post continues our series of OpenLayers tutorials. If you are new to OpenLayers, review our basic map setup tutorial before continuing.

A common task of any mapping application is to place a marker at a specified location. OpenLayers provides several options for doing this but we will focus on using a Marker.

Our simple example will allow a user to plot the location of various US cities on an OpenLayers map. In order to accomplish this, we need to know the longitude (X) and latitude (Y) of each city. We will use this list of city coordinates to create a HTML <select> box.

<select id="jumpTo" onchange="jumpTo();">
    <option value="NA">=== Select a City ===</option>
    <option value="-84.42,33.65">Atlanta</option>
    <option value="-104.87,39.75">Denver</option>  
    <option value="-95.35,29.97">Houston</option>
    <option value="-81.32,28.43">Orlando</option> 
    <option value="-121.50,38.52">Sacramento</option>
    <option value="-95.62,39.07">Topeka</option> 
</select>


Each <option> uses the value attribute to store the city’s coordinates. Note that the longitude coordinate is listed first and uses a negative number because we are in the western hemisphere.

We also added a javascript function call jumpTo that is called when the selected value is changed. This is where we will use OpenLayers to place a marker on the map.

Our OpenLayers map will be a single HTML page that is based on our basic map setup tutorial. We next need to add a variable to track the markers. This will be placed in the <head> along with some basic OpenLayers initialization code.

<script type="text/javascript">
    var map, baseLayer, markers;
    function init(){
        map = new OpenLayers.Map('map');            
        baseLayer = new OpenLayers.Layer.WMS("OpenLayers VMAP0", "http://labs.metacarta.com/wms/vmap0", {layers:"basic"});
        map.addLayer(baseLayer);
        map.setCenter(new OpenLayers.LonLat(-98, 39),3); 
        markers = new OpenLayers.Layer.Markers("Cities");   			
        map.addLayer(markers);            
    }

Within the init() function, the markers layer is added to the map.

markers = new OpenLayers.Layer.Markers("Cities");   			
map.addLayer(markers);

Below that we need to add the jumpTo() function to place a marker on the selected city.

function jumpTo()
{
    markers.clearMarkers();                
    var selectBox = document.getElementById('jumpTo');        		
    if (selectBox.value == "NA") return;
    var parse = selectBox.value.split(',');
    var location = new OpenLayers.LonLat(parse[0],parse[1]); 			
    var size = new OpenLayers.Size(21,25);
    var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
    var icon = new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png',size,offset);
    markers.addMarker(new OpenLayers.Marker(location,icon.clone()));               			
}
</script>

The code first accesses the select box and makes sure the user selected a city. It next collects the coordinates and parses them based on the comma in between. It then creates a LonLat object based on the parsed coordinates.

The next three lines define the marker’s icon and ensures that the marker point is placed exactly on the location (this code comes from the OpenLayers marker example). OpenLayers has markers in several colors which you can view here. All of them are 21×25 pixels in size but if you were to use your own image, be sure to change the size definition in the code.

The entire HTML code should look like this:

<!DOCTYPE html>
<html>
  <head>
    <title>OpenLayers Tutorial - Place a Marker</title>
    <script src="http://openlayers.org/api/OpenLayers.js"></script>
    <script type="text/javascript">
        var map, baseLayer, markers;
        function init(){
            map = new OpenLayers.Map('map');            
            baseLayer = new OpenLayers.Layer.WMS("OpenLayers VMAP0", "http://labs.metacarta.com/wms/vmap0", {layers:"basic"});
            map.addLayer(baseLayer);
            map.setCenter(new OpenLayers.LonLat(-98, 39),3); 
   	    markers = new OpenLayers.Layer.Markers("Cities");   			
            map.addLayer(markers);            
        }
 
        function jumpTo()
        {
            markers.clearMarkers();        	
            var selectBox = document.getElementById('jumpTo');        		
   	    if (selectBox.value == "NA") return;
   	    var parse = selectBox.value.split(',');
   	    var location = new OpenLayers.LonLat(parse[0],parse[1]); 			
   	    var size = new OpenLayers.Size(21,25);
            var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
            var icon = new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png',size,offset);   
            markers.addMarker(new OpenLayers.Marker(location,icon.clone()));               			 
          }
    </script>
 
    <style>
    @media screen
    {
        #map{width: 500px; height:300px; border: 2px solid black;}
    }
    </style>
  </head>
  <body onload="init()">
    <h1>OpenLayers Tutorial - Place a Marker</h1>
    <div id="map"></div>
    <br />
    <label>Place a marker at this city: </label>
    <select id="jumpTo" onchange="jumpTo();">
        <option value="NA">=== Select a City ===</option>
    	<option value="-84.42,33.65">Atlanta</option>
    	<option value="-104.87,39.75">Denver</option>  
    	<option value="-95.35,29.97">Houston</option>
    	<option value="-81.32,28.43">Orlando</option> 
    	<option value="-121.50,38.52">Sacramento</option>
    	<option value="-95.62,39.07">Topeka</option> 
    </select>
  </body>
</html>

Opening the web page should produce something like this:

Click here to view the final result in a new window