Open Layer with MapSever


Openlayer can add mapserver wms layer. In this writing, I discuss how work with mapserver wms layer using openlayer. I also wrote an article on how to create mapserver wms repository in my another writing here.

So let assume that we have a well configure mapserver repository and now want to view this maps using openlayer.

Add MapSever WMS Layer:

var dist = new OpenLayers.Layer.WMS( "Bangladesh Admin Bourndary",
	 "http://localhost:8080/cgi-bin/mapserv.exe?map=C:/OSGeo4W/apache/htdocs/openlayer/sampleapps/distwms.map",
	{layers: 'dist_geo',
		srs: 'EPSG:4326',
		format: format,
		isBaseLayer: true,
		visibility: true
	}

);
 

This will include Bangladesh district boundary as base wms layer. Note that we set the srs value wgs84 projection of our data.

Now we add the road layer from wms as openlayer overlay layer.

 // add road layer as overlay layer
	var bdhw = new OpenLayers.Layer.WMS(
                "Bangladesh Highway",
                "http://localhost:8080/cgi-bin/mapserv.exe",
                {
                    map: 'C:/OSGeo4W/apache/htdocs/openlayer/sampleapps/distwms.map',
                    transparent: 'TRUE',
                    layers: 'road_geo',
	    srs: 'EPSG:4326',
	   format: format
                },
                {'reproject': true}
            );

Now we implement identity features. When user click on map, we make WMSGetFeatureInfo request to mapserver.


infoControls = {
	click: new OpenLayers.Control.WMSGetFeatureInfo({
	url: 'http://localhost:8080/cgi-bin/mapserv.exe?map=C:/OSGeo4W/apache/htdocs/openlayer/sampleapps/distwms.map',
	title: 'Identify features by clicking',
	layers: [dist],
	infoFormat:'text/html',
	queryVisible: true
	})
};

Below the full source code is available,

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>MapServer Layer</title>
    <link rel="stylesheet" href="theme/default/style.css" type="text/css" />
    <style>
		.opmap
		{
			height:450px;
			width:550px;
		}
    </style>
    <script src="OpenLayers.js"></script>
    <script src='http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAjpkAC9ePGem0lIq5XcMiuhR_wWLPFku8Ix9i2SXYRVK3e45q1BQUd_beF8dtzKET_EteAjPdGDwqpQ'></script>
    <script type="text/javascript">

		/*######################
		Author: Md Abul Khayer
		Year: 2010
		khayer.wordpress.com
		#######################*/

        var map, layer;
		var infoControls;

        function init(){

			format = 'image/png';

			var bounds = new OpenLayers.Bounds(
				88.011, 20.59,
				92.683, 26.634
			);

			var options = {
				controls: [],
				maxExtent: bounds,
				maxResolution: 0.023609375,
				projection: "EPSG:4326",
			};

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

			// Add Google Layer as baselayer
			var gphy = new OpenLayers.Layer.Google(
			"Google Physical",
			{type: G_PHYSICAL_MAP}
            );

			var gmap = new OpenLayers.Layer.Google(
                "Google Streets", // the default
                {numZoomLevels: 20}
            );

			var ghyb = new OpenLayers.Layer.Google(
                "Google Hybrid",
                {type: G_HYBRID_MAP, numZoomLevels: 20}
            );

			var gsat = new OpenLayers.Layer.Google(
                "Google Satellite",
                {type: G_SATELLITE_MAP, numZoomLevels: 22}
            );

            map.addLayers([gphy, gmap, ghyb, gsat]);

			// Add Custom base layer. Bangladesh District boundary.
			var dist = new OpenLayers.Layer.WMS( "Bangladesh Admin Bourndary",
                    "http://localhost:8080/cgi-bin/mapserv.exe?map=C:/OSGeo4W/apache/htdocs/openlayer/sampleapps/distwms.map",
					{layers: 'dist_geo',
						srs: 'EPSG:4326',
						format: format,
						isBaseLayer: true,
						visibility: true
					}

			);

            // add road layer as overlay layer
			var bdhw = new OpenLayers.Layer.WMS(
                "Bangladesh Highway",
                "http://localhost:8080/cgi-bin/mapserv.exe",
                {
                    map: 'C:/OSGeo4W/apache/htdocs/openlayer/sampleapps/distwms.map',
                    transparent: 'TRUE',
                    layers: 'road_geo',
					srs: 'EPSG:4326',
					format: format
                },
                {'reproject': true}
            );

            // Bangladesh distric head queater as overlay layer.
			var bdhq = new OpenLayers.Layer.WMS(
                "Bangladesh Dist HQ",
                "http://localhost:8080/cgi-bin/mapserv.exe",
                {
                    map: 'C:/OSGeo4W/apache/htdocs/openlayer/sampleapps/distwms.map',
                    transparent: 'TRUE',
                    layers: 'dist_hq_geo',
					srs: 'EPSG:4326',
					format: format
                },
                {'reproject': true}
            );

			// Get identities of the map. Can be either click or hover is activated.
			infoControls = {
				click: new OpenLayers.Control.WMSGetFeatureInfo({
					url: 'http://localhost:8080/cgi-bin/mapserv.exe?map=C:/OSGeo4W/apache/htdocs/openlayer/sampleapps/distwms.map',
					title: 'Identify features by clicking',
					layers: [dist],
					infoFormat:'text/html',
					queryVisible: true
				}),
            	hover: new OpenLayers.Control.WMSGetFeatureInfo({
                url: 'http://localhost:8080/cgi-bin/mapserv.exe?map=C:/OSGeo4W/apache/htdocs/openlayer/sampleapps/distwms.map',
                title: 'Identify features by clicking',
                layers: [dist],
                hover: true,
				infoFormat: 'text/html',
                queryVisible: true
            	})
			}

            map.addLayers([dist, bdhw, bdhq]);
			map.zoomToMaxExtent();
            map.addControl( new OpenLayers.Control.LayerSwitcher() );
			map.addControl(new OpenLayers.Control.Navigation());
			map.addControl(new OpenLayers.Control.LayerSwitcher({'div':OpenLayers.Util.getElement('layerswitcher')}));

			map.addControl(new OpenLayers.Control.Scale($('scale')));
			map.addControl(new OpenLayers.Control.MousePosition({element: $('location')}));

			for (var i in infoControls) {
				infoControls[i].events.register("getfeatureinfo", this, showInfo);
				map.addControl(infoControls[i]);
			}

        	infoControls.click.activate();

        }

		function showInfo(evt) {
			if (evt.features && evt.features.length) {
				 //highlightLayer.destroyFeatures();
				 //highlightLayer.addFeatures(evt.features);
				 //highlightLayer.redraw();

				 $('nodelist').innerHTML=evt.text;
			} else {
				$('nodelist').innerHTML=evt.text;
			}
    	}

    </script>
  </head>

  <body onLoad="init()">
    <div id="title">MapServer WMS Layer with Google map.</div>
    <div id="layerswitcher" class="olControlLayerSwitcher"></div>
    <div id="map" class="opmap"></div>

    <div id="wrapper">
        <div id="location" style="float:left">location</div>
        <div id="scale" style="float:left"></div>
        <div id="scale" style="clear:both"></div>
    </div>
    <div id="nodelist">
        <em>Click on the map to get feature info</em>
    </div>

  </body>
</html>

………………………………………………
Abul Khayer
GIS Programmer
CEGIS

7 thoughts on “Open Layer with MapSever

  1. hi khayer,

    I am quite new to MapServer, actually new in GIS as well. I am trying to integrate Openlayer to MapServer and was looking for some basic examples. I find your application quite useful. It would be good for me if you could provide your Map file (distwms.map/distGeo.map).

    Thanks!

  2. Hello

    I came across your blog dealing with mapserver and openlayers. I am stuck with one problem, when I am using openlayers to display my mapserver file, it is displaying only one single point. Whereas the using map server alone it is creating image file correctly.

    I will be very grateful if you can help me as soon as possible.

    Code for adding layer in openlayer:

    var mlayer = new OpenLayers.Layer.MapServer( “Map Server”,
    “http://localhost/cgi-bin/mapserv.exe”,
    { map:’/var/www/ganga/ganga.map’,
    format:’png’,
    layers:’my_shapefile’,
    srs: ‘EPSG:4326’
    }
    );

    Map Layer:

    MAP
    NAME “img”
    SIZE 400 300
    SYMBOLSET “/var/www/ganga/symbol.sym”
    IMAGECOLOR 249 245 186
    IMAGETYPE png
    WEB
    TEMPLATE “/var/www/ganga/test.html”
    IMAGEPATH “/var/www/ganga/”
    END
    EXTENT 78.050000 26.610000 80.270000 29.040000
    LAYER
    NAME my_shapefile
    TYPE POINT
    DATA dolphin_1st
    STATUS default
    PROJECTION
    “init=epsg:4326”
    END
    CLASS
    STYLE
    SYMBOL “circle”
    SIZE 7
    END
    NAME “dolphin”
    OUTLINECOLOR 0 100 0
    END
    END
    END

    Thanks

    Varunesh Mishra

  3. I had difficulty loading mapserver data from our Ubuntu server onto openlayers. This is code of how we resolved it – you might have to change the mapserver WMS settings. We created the map file from QGIS (with the “export to MapFile” plugin), and then edited it, specifically the EPSG projections.

    var map;

    function init() {
    // Setup our map object
    map = new OpenLayers.Map(‘map_element’,{projection:’EPSG:900913′,
    maxExtent: new OpenLayers.Bounds(-20037508, -20037508,
    20037508, 20037508),
    units: ‘m’
    });

    //google terrain base layer
    var gmap = new OpenLayers.Layer.Google(
    “Google Terrain”,
    {type: google.maps.MapTypeId.TERRAIN}
    // default type, no change needed here
    );

    natpk = new OpenLayers.Layer.WMS(“Layer Name”,
    “http://localhost/cgi-bin/mapserv”,
    {map:’/xyz/www/Test.map’,
    layers: (‘nationalPark’),
    visibility: false,
    format:’image/png’
    },{
    isBaseLayer: false,
    opacity: 0.7,
    visibility: false
    });

    map.addLayers([gmap, wms_layer_map, htgWorld, htgSOI,EaNG, cSd, oFNS, natpk, provPark, clabIRS, areaInt, sHTGpn]);

    MAP
    NAME “MAP_NAME” # Spaces are allowed but not permitted for WMS and WFS
    # Map image size
    STATUS ON
    SIZE 400 300
    UNITS meters

    EXTENT 1120700 651500 1272200 982500
    FONTSET ‘./fonts/fontset.txt’
    SYMBOLSET ‘./symbols/symbols.txt’
    SHAPEPATH ‘./data’
    TRANSPARENT ON
    END

    IMAGECOLOR 255 255 255
    IMAGEQUALITY 95
    IMAGETYPE png

    OUTPUTFORMAT
    NAME png
    DRIVER ‘GD/PNG’
    MIMETYPE ‘image/png’
    IMAGEMODE PC256
    EXTENSION ‘png’
    END

    WEB
    IMAGEPATH ‘./tmp/’
    IMAGEURL ‘/tmp/’
    TEMPLATE ‘./template/blank.html’

    METADATA #THIS IS VERY IMPORTANT
    “wms_title” “WMS title for our map”
    “wms_onlineresource” “http://yoursource/cgi-bin/mapserv?map=/var/www/htgTest_WMS.map&”
    “wms_srs” “EPSG:4326 EPSG:900913”
    “ows_srs” “EPSG:4326 EPSG:900913”
    “ows_enable_request” “*”
    “wms_enable_request” “*”
    “wms_getcapabilities_version” “1.1.0”
    “wms_feature_info_mime_type” “text/html”
    “wms_featureid” “oid”
    “gml_include_items” “all”
    “wms_inlude_items” “all”
    END

    LAYER # 1
    NAME ‘nationalPark’
    TYPE POLYGON.
    #CONNECTIONTYPE postgis
    #CONNECTION “dbname=’yourPostGISdbName’ host=localhost port=5432 user=’you’ password=’yourpswd’ sslmode=disable”
    #DATA ‘the_geom FROM nationalPark’
    DATA ‘nationalPark’
    METADATA
    “wms_title” “National Park”
    “wms_onlineresource” “http://yourwebsite/cgi-bin/mapserv?GetMap=/var/www/Test.map&”
    “wms_srs” “EPSG:3005”
    “wms_enable_request” “*”
    “gml_inlude_items” “all”
    “wms_inlude_items” “all”
    END
    STATUS OFF
    TEMPLATE “blank.html” ## Needs some sort of template in order to be queryable
    DUMP TRUE
    PROJECTION
    “init=epsg:3005”
    END
    CLASS
    NAME ‘National Park’
    STYLE
    WIDTH 0.91
    OUTLINECOLOR 0 0 0
    COLOR 51 63 138
    #COLOR -1 63 138
    END
    END
    END

    END

  4. Hello sir,
    Its a nice contents about openlayers. Actually I am new in this topic and trying to do one map project.
    the map I want to take from NLS ( National land Survey ) Finland – http://www.maanmittauslaitos.fi. I already have the username and password from the company, but I stuck on this HTTPS authentication thing actually how to sent the HTTPS request to the map company, the username and password should not be visible to the map users.Can you please give me a code example sir, I will be so grateful to you.
    Aryan

  5. Hi Khayer,
    Very nice blog. I am new to Geoserver. I know how to add layers to geoserver and view them using openlayers. Then i do a ctrl+U and copy the code into a html file which i place into my www folder in Geoserver. When i open this html file on the browser it works fine.
    My problem is….
    I want to add bing imagery or google imagery to this code, i am unable to make it work. I am unable to integrate the code i copied from Geoserver and code to adding imagery. Do you have any tips on this?

    Thanks
    Susan

  6. Hi Khayer

    I have three layer in which i want to refresh one layer (WMS) in open layer which contain data .

    Thanks

Leave a comment