Creating a simple OpenLayers Map

In OpenLayers, a map is a collection of layers and various controls for dealing with user interaction. A map is generated with three basic elements: markup, style declarations, and map initialization code.

Working Example

Let’s take a look at a fully working example of an OpenLayers map.

<html>
   <head>
         <title>Counties of Colorado</title>
         <link rel="stylesheet" href="lib/openlayers/theme/default/style.css" type="text/css">
         <style>
                 #map-id {
                         width: 512px;
                         height: 300px;
                 }
         </style>
         <script src="lib/openlayers/OpenLayers.js"></script>
        </head>
        <body>
         <h1>Counties of Colorado</h1>
         <div id="map-id"></div>
         <script>
                 var bounds = new OpenLayers.Bounds(
                        -109.06, 36.992,
                        -102.041, 41.003
                 );

                 var options = {
                                 controls: [],
                                 maxExtent: bounds,
                                 maxResolution: 0.02741796875,
                                 projection: "EPSG:4269",
                                 units: 'm'
                 };

                 map = new OpenLayers.Map('map-id', options);

                 var ccounties = new OpenLayers.Layer.WMS(
                                 "Counties of Colorado - Untiled", "http://localhost:8083/geoserver/wms",
                                 {
                                         srs: 'EPSG:4269',
                                         layers: 'geosolutions:Counties',
                                         styles: '',
                                         format:'image/png'
                                 },
                                 {singleTile: true, ratio: 1}
                 );

                 map.addLayer(ccounties);

                 // build up all controls
                 map.addControl(new OpenLayers.Control.PanZoomBar({
                         position: new OpenLayers.Pixel(2, 15)
                 }));
                 map.addControl(new OpenLayers.Control.Navigation());
                 map.addControl(new OpenLayers.Control.Scale());
                 map.addControl(new OpenLayers.Control.MousePosition());
                 map.zoomToExtent(bounds);

         </script>
        </body>
</html>
  1. Copy the text above into a new file called index.html, and save it in the $TRAINING_ROOT/tomcat-7.0.72/instances/instance1/webapps/Map folder ( %TRAINING_ROOT%\tomcat-7.0.72\instances\instance1\webapps\Map on Windows ).

  2. Open the working map in your web browser at Welcome Page.

    ../_images/ol1.png

    A working map of displaying imagery Counties of Colorado