A Mapping Site in 19 Lines of Code
In another article this month we looked at the relatively easy steps to get MapServer installed on Windows/IIS. Now let’s take it a step further and make a map, complete with panning and zooming. PHP/Mapscript makes this fantastically easy, with only 19 lines of code! You can download the code here.
In the mapserver_sample folder you have two files and a folder. The folder contains a single shape file of Mecklenburg County’s voting precincts. The default.php file is our web page, and the sample_map.map is a map configuration file. Let’s look at the map configuration file first.
For those used to development in ArcIMS, MapServer’s map file is the equivalent of an AXL file in ArcIMS. It points to your data and applies some general metadata to it (what to shade or label things, projection information, etc.). For this example, ours is relatively simple. One thing to note is this bit of code:
WEB
IMAGEPATH “c:\inetpub\wwwroot\tmp_image"
IMAGEURL “/tmp_image/“
END
Like ArcIMS, MapServer creates an image of the map you request. Here we’re telling it to write the image to a directory (c:\inetpub\wwwroot\tmp_image) you’ll need to create. The second line, by beginning with a ‘/‘, tells the MapServer that the URL to the image folder will start at root (i.e. http://Your_Server_Name/tmp_image/). Then you’ll need to give the login IIS uses write permission to that folder. Right-click on the folder and select the Security tab. Click Add, and change the “from this location” to your workstation or server. Enter the IIS anonymous user name (iusr_yourmachine), and give it write access. After that, we’re done. MapServer configuration files are fairly readable (especially when compared to XML in an AXL file), and they can have all kinds of settings we won’t get in to here. For more information on MapServer configuration files, look here. There is also a free suite of WYSIWYG tools to create MapServer configuration files here.
The code in the default.php file itself should give you an idea of just how easy MapServer development can be. To produce a map with pan/zoom capabilities takes only 19 lines of code (maybe less if you’re a better PHP hack than the PC). As the code is commented and the variables are named more or less what they are, there’s not much for me to explain. The $map->zoompoint function actually handles zooming and panning - panning having a zoom factor of 1, it simply recenters the map. For you JavaScript wizards with zoom boxes you’d use $map->zoomrectangle. How simple is that?
Of course, you probably wouldn’t dump this page on the Internet and begin shouting from the rooftops. The PC is working on a PHP/MapServer template for more realistic web development. When that’s done I’ll blog it and release the source code. Just don’t blame the PC if MapScript and PHP burdens you with lots of extra free time you have to fill.