[GIS] Building a thin mapping client with OpenLayers

geoserveropenlayers-2

I have installed GeoServer inside of Tomcat, imported my PostGIS tables into GeoServer and have created my styles etc. I can preview them using OpenLayers in GeoServer.

Now, I want to build a simple mapping client using OpenLayers. So I download the openlayer.x zip file, I unzipped it to my geoserver/data/www folder. My GeoServer instance sits inside the web apps folder of Tomcat. I also copied the wms.html file from the OpenLayers example folder into this www folder as well and changed parameters like the src to point to my GeoServer instance, the layer and the openlayers.js path. This is following the instruction on this site:
https://www.e-education.psu.edu/geog585/l8_p5.html

However when I try to open mylayers.html, I don't see the layers which I specified to show. I only see the text and no map shown. Below is the code for my client (mylayers.html) which is saved in the www folder: I have removed the style parameter because of space limitation here, but the URL for style.css is localhost:8080/geoserver/OpenLayers-2.12/theme/default/style.css

<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
    <script src="http://localhost:8080/geoserver/OpenLayers-2.12/OpenLayers.js"   type="text/javascript">
    </script>
    <script defer="defer" type="text/javascript">
        var map;
        var Layer1, Layer2, Layer3, Layer4, Layer5, Layer6, Layer7, Layer8, Layer9, Layer10, Layer11, Layer12;
        var pureCoverage = false;
        // pink tile avoidance
        OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
        // make OL compute scale according to WMS spec
        OpenLayers.DOTS_PER_INCH = 25.4 / 0.28;

        function init(){
            // if this is just a coverage or a group of them, disable a few items,
            // and default to jpeg format
            format = 'image/png';
            if(pureCoverage) {
                document.getElementById('filterType').disabled = true;
                document.getElementById('filter').disabled = true;
                document.getElementById('antialiasSelector').disabled = true;
                document.getElementById('updateFilterButton').disabled = true;
                document.getElementById('resetFilterButton').disabled = true;
                document.getElementById('jpeg').selected = true;
                format = "image/jpeg";
            }

            var bounds = new OpenLayers.Bounds(
                143.971463002, -8.04166701399993,
                151.699865035, -3.99888201799996
            );
            var options = {
                controls: [],
                maxExtent: bounds,
                maxResolution: 0.0301890704414062,
                projection: "EPSG:4326",
                units: 'degrees'
            };
            map = new OpenLayers.Map('map', options);


            Layer1 = new OpenLayers.Layer.WMS("Trial1:province - Untiled",    "http://localhost:8080/geoserver/wms",
                {
                    layers: 'Trial1:province',
                    styles: '',
                    format: 'format'
                    width:'800'
                    height:'300'
                    srs: 'EPSG:4326'
                },
                {
                   singleTile: true, 
                   ratio: 1, 
                   isBaseLayer: true,
                } 
            );

            layer2 = new OpenLayers.Layer.WMS(
                "Trial1:vct_sites - Untiled", "http://localhost:8080/geoserver/wms",
                {
                    layers: 'Trial1:vct_sites',
                    styles: '',
                    format: 'format''
                    width:'800'
                    height:'300'
                    srs: 'EPSG:4326'
                    transparent: true
                },
                {
                   singleTile: true, 
                   ratio: 1, 
                   isBaseLayer: false,

                } 
            );

            Layer3 = new OpenLayers.Layer.WMS(
                "Trial1:road_network - Untiled", "http://localhost:8080/geoserver/wms",
                {
                    layers: 'Trial1:road_network',
                    styles: '',
                    format: 'format''
                    width:'800'
                    height:'300'
                    srs: 'EPSG:4326'
                    transparent: true
                },
                {
                   singleTile: true, 
                   ratio: 1, 
                   isBaseLayer: false,

                } 
            );

             Layer4 = new OpenLayers.Layer.WMS(
                "Trial1:major_towns - Untiled", "http://localhost:8080/geoserver/wms",
                {
                    layers: 'Trial1:major_towns',
                    styles: '',
                    format: 'format''
                    width:'800'
                    height:'300'
                    srs: 'EPSG:4326'
                    transparent: true
                },
                {
                   singleTile: true, 
                   ratio: 1, 
                   isBaseLayer: false,

                } 
            );

             Layer5 = new OpenLayers.Layer.WMS(
                "Trial1:llg - Untiled", "http://localhost:8080/geoserver/wms",
                {
                    layers: 'Trial1:llg',
                    styles: '',
                    format: 'format''
                    width:'800'
                    height:'300'
                    srs: 'EPSG:4326'
                    transparent: true
                },
                {
                   singleTile: true, 
                   ratio: 1, 
                   isBaseLayer: false,

                } 
            );

            Layer6 = new OpenLayers.Layer.WMS(
                "Trial1:health_centers - Untiled", "http://localhost:8080/geoserver/wms",
                {
                    layers: 'Trial1:health_centers',
                    styles: '',
                    format: 'format''
                    width:'800'
                    height:'300'
                    srs: 'EPSG:4326'
                    transparent: true
                },
                {
                   singleTile: true, 
                   ratio: 1, 
                   isBaseLayer: true,

                } 
            );

            Layer7 = new OpenLayers.Layer.WMS(
                "Trial1:hc_ap_links - Untiled", "http://localhost:8080/geoserver/wms",
                {
                    layers: 'Trial1:hc_ap_links',
                    styles: '',
                    format: 'format''
                    width:'800'
                    height:'300'
                    srs: 'EPSG:4326'
                    transparent: true
                },
                {
                   singleTile: true, 
                   ratio: 1, 
                   isBaseLayer: false,

                } 
            );

            Layer8 = new OpenLayers.Layer.WMS(
                "Trial1:district - Untiled", "http://localhost:8080/geoserver/wms",
                {
                     layers: 'Trial1:district',
                    styles: '',
                    format: 'format''
                    width:'800'
                    height:'300'
                    srs: 'EPSG:4326'
                    transparent: true
                },
                {
                   singleTile: true, 
                   ratio: 1, 
                   isBaseLayer: false,

                } 
            );

            Layer9 = new OpenLayers.Layer.WMS(
                "Trial1:census_units - Untiled", "http://localhost:8080/geoserver/wms",
                {
                    layers: 'Trial1:census_units',
                    styles: '',
                    format: 'format''
                    width:'800'
                    height:'300'
                    srs: 'EPSG:4326'
                    transparent: true
                },
                {
                   singleTile: true, 
                   ratio: 1, 
                   isBaseLayer: false,

                } 
            );

            Layer10 = new OpenLayers.Layer.WMS(
                "Trial1:areastore_hc_links - Untiled", "http://localhost:8080/geoserver/wms",
                {
                    layers: 'Trial1:areastore_hc_links',
                    styles: '',
                    format: 'format''
                    width:'800'
                    height:'300'
                    srs: 'EPSG:4326'
                    transparent: true
                },
                {
                   singleTile: true, 
                   ratio: 1, 
                   isBaseLayer: false,

                } 
            );

            Layer11 = new OpenLayers.Layer.WMS(
                "Trial1:airstrips - Untiled", "http://localhost:8080/geoserver/wms",
                {
                    layers: 'Trial1:airstrips',
                    styles: '',
                    format: 'format''
                    width:'800'
                    height:'300'
                    srs: 'EPSG:4326'
                    transparent: true
                },
                {
                   singleTile: true, 
                   ratio: 1, 
                   isBaseLayer: false,

                } 
            );

             Layer12 = new OpenLayers.Layer.WMS(
                "Trial1:aidpost - Untiled", "http://localhost:8080/geoserver/wms",
                {
                    layers: 'Trial1:aidpost',
                    styles: '',
                    format: 'format''
                    width:'800'
                    height:'300'
                    srs: 'EPSG:4326'
                    transparent: true
                },
                {
                   singleTile: true, 
                   ratio: 1, 
                   isBaseLayer: false,

                } 
            );


            map.addLayers([Layer1, Layer2, Layer3, Layer4, Layer5, Layer6, Layer7, Layer8, Layer9, Layer10, Layer11, Layer12]);

            // 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($('scale')));
            map.addControl(new OpenLayers.Control.MousePosition({element: $('location')}));
            map.zoomToExtent(bounds);

            // wire up the option button
            var options = document.getElementById("options");
            options.onclick = toggleControlPanel;

            // support GetFeatureInfo
            map.events.register('click', map, function (e) {
                document.getElementById('nodelist').innerHTML = "Loading... please wait...";
                var params = {
                    REQUEST: "GetFeatureInfo",
                    EXCEPTIONS: "application/vnd.ogc.se_xml",
                    BBOX: map.getExtent().toBBOX(),
                    SERVICE: "WMS",
                    INFO_FORMAT: 'text/html',
                    QUERY_LAYERS: map.layers[0].params.LAYERS,
                    FEATURE_COUNT: 50,
                    Layers: 'Trial1:province',
                    WIDTH: map.size.w,
                    HEIGHT: map.size.h,
                    format: format,
                    styles: map.layers[0].params.STYLES,
                    srs: map.layers[0].params.SRS};

                // handle the wms 1.3 vs wms 1.1 madness
                if(map.layers[0].params.VERSION == "1.3.0") {
                    params.version = "1.3.0";
                    params.j = parseInt(e.xy.x);
                    params.i = parseInt(e.xy.y);
                } else {
                    params.version = "1.1.1";
                    params.x = parseInt(e.xy.x);
                    params.y = parseInt(e.xy.y);
                }

                // merge filters
                if(map.layers[0].params.CQL_FILTER != null) {
                    params.cql_filter = map.layers[0].params.CQL_FILTER;
                } 
                if(map.layers[0].params.FILTER != null) {
                    params.filter = map.layers[0].params.FILTER;
                }
                if(map.layers[0].params.FEATUREID) {
                    params.featureid = map.layers[0].params.FEATUREID;
                }
                OpenLayers.loadURL("http://localhost:8080/geoserver/Trial1/wms", params, this, setHTML, setHTML);
                OpenLayers.Event.stop(e);
            });
        }

        // sets the HTML provided into the nodelist element
        function setHTML(response){
            document.getElementById('nodelist').innerHTML = response.responseText;
        };

        // shows/hide the control panel
        function toggleControlPanel(event){
            var toolbar = document.getElementById("toolbar");
            if (toolbar.style.display == "none") {
                toolbar.style.display = "block";
            }
            else {
                toolbar.style.display = "none";
            }
            event.stopPropagation();
            map.updateSize()
        }

        // Tiling mode, can be 'tiled' or 'untiled'
        function setTileMode(tilingMode){
            if (tilingMode == 'tiled') {
                untiled.setVisibility(false);
                tiled.setVisibility(true);
                map.setBaseLayer(tiled);
            }
            else {
                untiled.setVisibility(true);
                tiled.setVisibility(false);
                map.setBaseLayer(untiled);
            }
        }

        // Transition effect, can be null or 'resize'
        function setTransitionMode(transitionEffect){
            if (transitionEffect === 'resize') {
                tiled.transitionEffect = transitionEffect;
                untiled.transitionEffect = transitionEffect;
            }
            else {
                tiled.transitionEffect = null;
                untiled.transitionEffect = null;
            }
        }

        // changes the current tile format
        function setImageFormat(mime){
            // we may be switching format on setup
            if(tiled == null)
              return;

            tiled.mergeNewParams({
                format: mime
            });
            untiled.mergeNewParams({
                format: mime
            });
            /*
            var paletteSelector = document.getElementById('paletteSelector')
            if (mime == 'image/jpeg') {
                paletteSelector.selectedIndex = 0;
                setPalette('');
                paletteSelector.disabled = true;
            }
            else {
                paletteSelector.disabled = false;
            }
            */
        }

        // sets the chosen style
        function setStyle(style){
            // we may be switching style on setup
            if(tiled == null)
              return;

            tiled.mergeNewParams({
                styles: style
            });
            untiled.mergeNewParams({
                styles: style
            });
        }

        // sets the chosen WMS version
        function setWMSVersion(wmsVersion){
            // we may be switching style on setup
            if(wmsVersion == null)
              return;

            if(wmsVersion == "1.3.0") {
               origin = map.maxExtent.bottom + ',' + map.maxExtent.left;
            } else {
               origin = map.maxExtent.left + ',' + map.maxExtent.bottom;
            }

            tiled.mergeNewParams({
                version: wmsVersion,
                tilesOrigin : origin
            });
            untiled.mergeNewParams({
                version: wmsVersion
            });
        }

        function setAntialiasMode(mode){
            tiled.mergeNewParams({
                format_options: 'antialias:' + mode
            });
            untiled.mergeNewParams({
                format_options: 'antialias:' + mode
            });
        }

        function setPalette(mode){
            if (mode == '') {
                tiled.mergeNewParams({
                    palette: null
                });
                untiled.mergeNewParams({
                    palette: null
                });
            }
            else {
                tiled.mergeNewParams({
                    palette: mode
                });
                untiled.mergeNewParams({
                    palette: mode
                });
            }
        }

        function setWidth(size){
            var mapDiv = document.getElementById('map');
            var wrapper = document.getElementById('wrapper');

            if (size == "auto") {
                // reset back to the default value
                mapDiv.style.width = null;
                wrapper.style.width = null;
            }
            else {
                mapDiv.style.width = size + "px";
                wrapper.style.width = size + "px";
            }
            // notify OL that we changed the size of the map div
            map.updateSize();
        }

        function setHeight(size){
            var mapDiv = document.getElementById('map');

            if (size == "auto") {
                // reset back to the default value
                mapDiv.style.height = null;
            }
            else {
                mapDiv.style.height = size + "px";
            }
            // notify OL that we changed the size of the map div
            map.updateSize();
        }

        function updateFilter(){
            if(pureCoverage)
              return;

            var filterType = document.getElementById('filterType').value;
            var filter = document.getElementById('filter').value;

            // by default, reset all filters
            var filterParams = {
                filter: null,
                cql_filter: null,
                featureId: null
            };
            if (OpenLayers.String.trim(filter) != "") {
                if (filterType == "cql") 
                    filterParams["cql_filter"] = filter;
                if (filterType == "ogc") 
                    filterParams["filter"] = filter;
                if (filterType == "fid") 
                    filterParams["featureId"] = filter;
            }
            // merge the new filter definitions
            mergeNewParams(filterParams);
        }

        function resetFilter() {
            if(pureCoverage)
              return;

            document.getElementById('filter').value = "";
            updateFilter();
        }

        function mergeNewParams(params){
            tiled.mergeNewParams(params);
            untiled.mergeNewParams(params);
        }
    </script>
</head>
<body onload="init()">
    <div id="toolbar" style="display: none;">
        <ul>
            <li>
                <a>WMS version:</a>
                <select id="wmsVersionSelector" onchange="setWMSVersion(value)">
                    <option value="1.1.1">1.1.1</option>
                    <option value="1.3.0">1.3.0</option>
                </select>
            </li>
            <li>
                <a>Tiling:</a>
                <select id="tilingModeSelector" onchange="setTileMode(value)">
                    <option value="untiled">Single tile</option>
                    <option value="tiled">Tiled</option>
                </select>
            </li>
            <li>
                <a>Transition effect:</a>
                <select id="transitionEffectSelector" onchange="setTransitionMode(value)">
                    <option value="">None</option>
                    <option value="resize">Resize</option>
                </select>
            </li>
            <li>
                <a>Antialias:</a>
                <select id="antialiasSelector" onchange="setAntialiasMode(value)">
                    <option value="full">Full</option>
                    <option value="text">Text only</option>
                    <option value="none">Disabled</option>
                </select>
            </li>
            <li>
                <a>Format:</a>
                <select id="imageFormatSelector" onchange="setImageFormat(value)">
                    <option value="image/png">PNG 24bit</option>
                    <option value="image/png8">PNG 8bit</option>
                    <option value="image/gif">GIF</option>
                    <option id="jpeg" value="image/jpeg">JPEG</option>
                </select>
            </li>
            <li>
                <a>Styles:</a>
                <select id="imageFormatSelector" onchange="setStyle(value)">
                    <option value="">Default</option>
                </select>
            </li>
            <!-- Commented out for the moment, some code needs to be extended in 
                 order to list the available palettes
            <li>
                <a>Palette:</a>
                <select id="paletteSelector" onchange="setPalette(value)">
                    <option value="">None</option>
                    <option value="safe">Web safe</option>
                </select>
            </li>
            -->
            <li>
                <a>Width/Height:</a>
                <select id="widthSelector" onchange="setWidth(value)">
                    <!--
                    These values come from a statistics of the viewable area given a certain screen area
                    (but have been adapted a litte, simplified numbers, added some resolutions for wide screen)
                    You can find them here: http://www.evolt.org/article/Real_World_Browser_Size_Stats_Part_II/20/2297/
                    --><option value="auto">Auto</option>
                    <option value="600">600</option>
                    <option value="750">750</option>
                    <option value="950">950</option>
                    <option value="1000">1000</option>
                    <option value="1200">1200</option>
                    <option value="1400">1400</option>
                    <option value="1600">1600</option>
                    <option value="1900">1900</option>
                </select>
                <select id="heigthSelector" onchange="setHeight(value)">
                    <option value="auto">Auto</option>
                    <option value="300">300</option>
                    <option value="400">400</option>
                    <option value="500">500</option>
                    <option value="600">600</option>
                    <option value="700">700</option>
                    <option value="800">800</option>
                    <option value="900">900</option>
                    <option value="1000">1000</option>
                </select>
            </li>
            <li>
                <a>Filter:</a>
                <select id="filterType">
                    <option value="cql">CQL</option>
                    <option value="ogc">OGC</option>
                    <option value="fid">FeatureID</option>
                </select>
                <input type="text" size="80" id="filter"/>
                <img id="updateFilterButton" src="http://localhost:8080/geoserver/OpenLayers-2.12/img/east-mini.png" onClick="updateFilter()" title="Apply filter"/>
                <img id="resetFilterButton" src="http://localhost:8080/geoserver/OpenLayers-2.12/img/cancel.png" onClick="resetFilter()" title="Reset filter"/>
            </li>
        </ul>
    </div>
    <div id="map">
        <img id="options" title="Toggle options toolbar" src="http://localhost:8080/geoserver/options.png"/>
    </div>
    <div id="wrapper">
        <div id="location">location</div>
        <div id="scale">
        </div>
    </div>
    <div id="nodelist">
        <em>Click on the map to get feature info</em>
    </div>
</body>
</html>

Using the Chrome developer tool – console, I see the following errors.

Failed to load resource: the server responded with a status of 404 (Not Found) 
Failed to load resource: the server responded with a status of 404 (Not Found) 
Uncaught SyntaxError: Unexpected identifier mylayers.html:150
Failed to load resource: the server responded with a status of 404 (Not Found) 
Failed to load resource: the server responded with a status of 404 (Not Found) 
Uncaught ReferenceError: init is not defined mylayers.html:632

What could be the problem here? as I'm sure my folders and files are where they should be.

Any help would be very much appreciated.

Best Answer

The URL to OpenLayers is wrong, try using this instead:

 <script src="http://localhost:8080/geoserver/www/OpenLayers-2.12/OpenLayers.js"   type="text/javascript">

Do the same for all other OpenLayers resources (i.e.: the images in the filter panel).

Related Question