Mapscript Demo (2)

June 2nd, 2007

Continuing with our exploring into Mapscript, our desktop mapping application needs some more setup. Our last post added a map file constant and now we will add two more variables to our form:

 

const string MAP_FILE = @"C:\ms4w\apps\gmap\htdocs\gmap75.map";
mapObj m_map;
rectObj m_fullExtent;

 

Both are Mapscript objects. The first (m_map) is our map object that will be the primary class used in this project. The second will simply remember the extent of the map upon startup, which is usually also the full extent of the map.

In the form’s constructor method, we setup our map to match our picture box size and the define the full extent:

 

m_map = new mapObj(MAP_FILE);
m_map.width = picMap.Width;
m_map.height = picMap.Height;
m_fullExtent = new rectObj(m_map.extent.minx, m_map.extent.miny,
                   m_map.extent.maxx, m_map.extent.maxy, 0);

 

Mapscript’s map object allows us to access Mapserver and generate map images. Here is one way to generate an image and load it into our picture box control. This code is based off a great Mapserver tutorial found here.

 

imageObj image = m_map.draw();
byte[] img = image.getBytes();
using (MemoryStream ms = new MemoryStream(img))
{
  picMap.Image = System.Drawing.Image.FromStream(ms);
}

 

Mapscript Image

Similarly, to generate a legend image:

 

imageObj legend = m_map.drawLegend();
byte[] img = legend.getBytes();
using (MemoryStream ms = new MemoryStream(img))
{
    picLegend.Image = System.Drawing.Image.FromStream(ms);
}

 

Mapscript Legend

Our application also has a sidebar that displays a legend that lists each layer and a check box displaying whether the layer is on or off. Each time the map is updated, this layers list needs to be updated by looping through the map’s layers and finding their visibility. A TreeView control is used to display the layers.

 

for (int i = m_map.numlayers - 1; i >= 0; i--)
{
    layerObj layer = m_map.getLayer(i);
    TreeNode node = new TreeNode(m_map.getLayer(i).name);
 
    if (layer.status == (int)mapscript.MS_ON)
        node.Checked = true;
    else
        node.Checked = false;
 
    trvLegend.Nodes.Add(node);
}

 

Map Layers List

The code samples above are each placed into separate functions appropriately named RefreshMap, RefreshMapLayers, and RefreshLegend. They will be called when the program starts up and each time the user interacts with the map. The last piece of the puzzle, adding the zooming and panning functionality, will be covered in the next post but the entire source code can be downloaded below.

Download Source Code

Continue to part 3