Click here to Skip to main content
15,886,137 members
Articles / Web Development / ASP.NET
Article

Building Scalable Mapping & GIS Apps with Web Services

14 Feb 2008CPOL7 min read 50.1K   28   1
These days, programmers need more control over the map data, map rendering, GIS capabilities, security and overall architecture. This article shows you how to build a scalable mapping application utilizing a web service and how to consume the web service from a client application.

This article is in the Product Showcase section for our sponsors at CodeProject. These articles are intended to provide you with information on products and services that we consider useful and of value to developers.

Image 1

Introduction

With the emergence of popular online mapping applications over the past few years, more businesses are seeing a need to build mapping and GIS (Geographic Information Systems) functionality into their own custom applications. While online services like Google Maps & Virtual Earth work well in some cases, many times programmers need more control over the map data, map rendering, GIS capabilities, security and overall architecture. In this article, I will show you how to build a scalable mapping application utilizing a web service and how to consume the web service from a client application.

Getting Started

Typically, when I get ready to build a new mapping application, I take a look at how the application will be used and try to break the map data into two separate categories:

  • Base Map – The base map is made up of the relatively static map data that you always want to show. Typically, these base maps are made up of common features like political boundaries, water features, roads and points of interest. For this example, I’m going to keep the base map very simple and just use an outline of the United States. If I wanted to use a more detailed base map, I would utilize one of the Map Suite Data Plugins to take care of the map data and rendering logic.
  • Dynamic Map Data – This type of map data changes frequently and will need to be updated regularly. Typically, this type of data is stored in a database that is updated by the application or other outside sources. In this example, I will again keep it simple and simulate plotting the location of two customers in the United States.

Now that you have an idea of the two different types of map data we will be dealing with, we can get started building the web service that will serve up our base maps.

The Web Service

The main goal we need to accomplish with this web service is to provide a high performance, scalable way to render the base maps. These base maps will then be consumed by our sample application. Encapsulating the logic to render the base maps into a web service allows us several advantages. These include centralized map data storage, map data only being loaded into memory once for all users, and finally, you can easily scale web services with a load balancer if demand grows.

To achieve maximum performance, we are going to utilize the Map Suite Engine Edition .NET component. This component will do the heavy lifting of rendering the map image that will be consumed by our sample application. To get started, you will need to create a new ASP.NET web service project in Visual Studio 2005. Once the new project is loaded, the first thing you will need to do is write the web service initialization code. To do this, you will need to add a Global.asax file to your web service. The Global.asax code below is where the MapEngine object is instantiated and the map data is loaded so it can be used for all web service requests.

Global.asax Code

C#
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using MapSuite;
 
namespace MapWebServiceExample
{
    public class Global : System.Web.HttpApplication
    {
 
        protected void Application_Start(object sender, EventArgs e)
        {
        
             //Instantiate  the MapEngine component
            MapEngine mapServer = new MapEngine();
            //Create the Layer Object that loads teh data for the USA outline.
            Layer stateLayer = new Layer(
                this.Server.MapPath("") + @"\SampleData\STATES.shp");
            //Set the color of the states to use the State1 geostyle
            GeoStyle stateGeoStyle = GeoAreaStyles.GetSimpleAreaStyle
                (GeoColor.GeographicColors.State1, GeoColor.KnownColors.Black);
            stateLayer.ZoomLevel01.GeoStyle = stateGeoStyle;
            //Apply this color & style to all zoom levels
            stateLayer.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.ZoomLevel18;
            //Add the state layer to the map
            mapServer.Layers.Add(stateLayer);
            //Store the map engine object to Application state
            Application.Add("mapServer", mapServer);
        }
 
        protected void Application_End(object sender, EventArgs e)
        {
            //Clear the applicatiion
            Application.Clear();
        }
    }
}

Now that we have written the code to initialize the web service, the next step is to create a WebMethod that our client application can call to retrieve the map image. To accomplish this, you will need to add a new web service page to your solution with an .asmx extension. For this example, I called the web service page MapService.asmx and exposed one public WebMethod called GetMapImage. The GetMapImage method takes in a few parameters so we can create the proper map image for the consuming application. These parameters include:

  • uLX - upper left x coordinate of the map image requested
  • uLY – upper left y coordinate of the map image requested
  • lRX – lower right x coordinate of the map image requested
  • lRY – lower right y coordinate of the map image requested
  • height – height of image requested
  • width – width of the image requested
  • quality – quality of compressed image returned

With these parameters, we can now create the specified map image in our web utilizing the map engine object that we initialized in the global.asax file. To see how this is accomplished, refer to the code below:

MapService.asmx Code

C#
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using MapSuite;
using MapSuite.Geometry;
 
namespace MapWebServiceExample
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    public class MapService : System.Web.Services.WebService
    {
    [WebMethod]
        public byte[] GetMapImage(double uLX, double uLY, double lRX, double lRY,
            int height, int width, short quality)      
        {
 
            // Handle threading and retrieve the map engine
            System.Threading.Monitor.Enter(Application["mapServer"]);
            MapEngine map1;
            map1 = Application["mapServer"] as MapEngine;
            //Create the Rectangle for the Map Area we want to return using cooridnates
            RectangleR fullExtent = new RectangleR(new PointR(uLX, uLY), new PointR(lRX,
                lRY));
            //Create new map bitmap and retrieve graphics object from it.
            Bitmap bmp = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(bmp);
            //Pass the graphic objects into the map engine to draw the image.
            map1.GetMap(g, fullExtent, width, height, MapLengthUnits.DecimalDegrees, 0);
            //Dispose of graphic object and handle threading
            g.Dispose();
            System.Threading.Monitor.Exit(Application["mapServer"]);
 
            //Create a new memory stream to hold the image
            MemoryStream MemoryStream = new MemoryStream();
 
            //Get codecs
            ImageCodecInfo[] icf = ImageCodecInfo.GetImageEncoders();
            EncoderParameters encps = new EncoderParameters(1);
            EncoderParameter encp = new EncoderParameter(Encoder.Quality, (long)quality);
 
            //Set quality and save the map to the memory stream
            encps.Param[0] = encp;
            bmp.Save(MemoryStream, icf[1], encps);
            MemoryStream.Close();
            //stream the image back to the client
            return MemoryStream.ToArray();
        }
    }
}

The Client Application

Now that we have the web service built, we move our focus onto the client application that will consume the web service and plot the customer locations. For this example, we are going to build a ASP.NET web application utilizing the Map Suite Web ASP.NET server control; however, the web service can be consumed just as easily in a desktop client application utilizing the Map Suite Desktop .NET control.

To get started, you will need to create a new ASP.NET web application in Visual Studio 2005. Next, you will need to reference the Map Suite Web Edition .NET Control and drag it on to the web page. Also, don’t forget to add the HTTP Handler section to your web.config file so the map control can render properly. Finally, you will need to add a web reference to the web service that was created earlier.

Once you have your application ready to start coding, you will need to put some code into the Page_Load event handler and the Map_BeforeLayerDraw event handler, along with some additional coding to display the customer points and handle zooming in and out. The Page_Load event handler code accomplishes a couple things. First, it sets the MapUnit property, which tells the map control which coordinate system to use. In this example, the coordinate system we will be working with is decimal degrees, also known as longitude & latitude coordinates. Next, we write some code to set the initial zoom level and default the map to pan mode. Finally, the last bit of code in the Page_Load calls the DisplayCustomerPoints function, which handles the task of displaying our dynamic customer points on the map.

You may be asking yourself, where does the web service fit in? By writing some code in the Map_BeforeLayersDraw event handler, we will be able to call the web service and draw our base map of the United States on the map control. To do this, we must first instantiate the web service and call the GetMapImage web method. Once we receive the byte array from the web service that contains the map image, the final task is to draw the map image on the map control using the graphics object passed into the event handler.

To make the application a little bit more user friendly, I have added “zoom in” and “zoom out” buttons to allow the user to zoom in and out. To see this code and all of the code mentioned above, please review the below:

Default.aspx Code

C#
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing;
using MapSuite;
using MapSuite.Geometry;
 
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Set our Map Unit so we can use longitude & latitude coordinates
            Map1.MapUnit = MapSuite.Geometry.MapLengthUnits.DecimalDegrees;
            //Tell the map control that we are going to control the extent
            Map1.AutoFullExtent = false;
            //Default the zoom/extent to show the lower 48 states
            Map1.CurrentExtent = new RectangleR(-125, 55, -66, 18);
            //Set the default mode of the map to panning
            Map1.Mode = MapSuite.WebEdition.Map.ModeType.Pan;
            //Enable Ajax capabilites for the map control
            Map1.AjaxEnabled = true;
            //Call the function so we can plot our customer points
            DisplayCustomerPoints();       
        }
    }
    protected void Map1_BeforeLayersDraw(System.Drawing.Graphics G)
    {
        //insantiate the webservice
        localhost.MapService MapMaker = new localhost.MapService();
        //call the GetMapImage WebMethod
        byte[] images = MapMaker.GetMapImage(Map1.CurrentExtent.UpperLeftPoint.X,
                                                Map1.CurrentExtent.UpperLeftPoint.Y,
                                                Map1.CurrentExtent.LowerRightPoint.X,
                                                Map1.CurrentExtent.LowerRightPoint.Y,
                                                Convert.ToInt32(Map1.Height.Value),
                                                Convert.ToInt32(Map1.Width.Value),
                                                -1);
        //Create a new Bitmap Object using the image stream
        MemoryStream MemoryStream = new MemoryStream(images);
        Bitmap NewImage = new Bitmap(MemoryStream);
        //Draw the image onto the map control
        G.DrawImageUnscaled(NewImage, 0, 0);
    }
 
    protected void DisplayCustomerPoints()
    {
        //Create a Dynamic Data Layer to hold our customers
        DynamicLayer customers = new DynamicLayer();
       
        //Create Customer Point for LA
        PointMapShape custLA = new PointMapShape(new PointShape(-118.24, 34.05));
        //Use a Graphic for the customer symbol
        PointSymbol symLA = new PointSymbol
                (new Bitmap(this.Server.MapPath("") + @"\images\customer.png"));
        custLA.ZoomLevel01.GeoStyle.SymbolRenderers.Add(new SymbolRenderer(symLA));
        //Lable the customer icon
        custLA.ZoomLevel01.GeoTextStyle = GeoTextStyles.GetSimpleTextStyle
                (null, "Arial", 9, GeoFontStyle.Bold, GeoColor.KnownColors.Black);
        //Apply to all zoom levels
        custLA.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.ZoomLevel18;
        //Name the Customer
        custLA.Name = "LA Customer";
        //Add the customer to the Dynamic Data Layer
        customers.MapShapes.Add(custLA);
 
        //Create Customer Point for KC
       PointMapShape custKC = new PointMapShape(new PointShape(-94.62, 39.11));
        //Use a Graphic for the customer symbol
        PointSymbol symKC = new PointSymbol
            (new Bitmap(this.Server.MapPath("") + @"\images\customermale.png"));
        custKC.ZoomLevel01.GeoStyle.SymbolRenderers.Add(new SymbolRenderer(symKC));
        //Lable the customer icon
        custKC.ZoomLevel01.GeoTextStyle = GeoTextStyles.GetSimpleTextStyle
            (null, "Arial", 9, GeoFontStyle.Bold, GeoColor.KnownColors.Black);
        //Apply to all zoom levels
        custKC.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.ZoomLevel18;
        //Name the Customer
        custKC.Name = "Kansas City Customer";
        //Add the customer to the Dynamic Data Layer
        customers.MapShapes.Add(custKC);
       
        //Add Dynamic Data Layer to Map Control   
        Map1.DynamicLayers.Add(customers);
    }
    protected void btnZoomIn_Click(object sender, EventArgs e)
    {
        //Zoom the map out 20%
        Map1.ZoomIn(20);
    }
    protected void btnZoomOut_Click(object sender, EventArgs e)
    {
        //Zoom the map out by 30%
        Map1.ZoomOut(30);
    }
}

Once you have all of this coding completed, you should be able to run your client application and get a result similar to the screen shot below:

image001.jpg

Summary

Leveraging web services can allow you to build extremely scalable mapping and GIS solutions. By utilizing the Map Suite Engine .NET Component in the web service, you can centralize all of your base map generation and large map datasets. In addition, you can still enjoy the developer experience of using the Map Suite ASP.NET & Desktop controls to handle all user interactions and display of dynamic map data, among other things. This article barely scratches the surface of what can be accomplished with mapping & GIS web services in conjunction with a rich user interface. The downloadable code can be used as a good starting point for building your own scalable .NET GIS mapping applications.

Downloads

Map Web Service & Client Example Code in C#

Map Suite Engine .NET Component & Web ASP.NET Control (Registration Required)

Note: You will need to download and install these Map Suite components in order to run the example in this article.

Have Questions?

Do you have questions or comments about this article? Feel free post your questions on the Map Suite Discussion Forums or leave feedback at the ThinkGeo Blog.

Additional Resources

Map Suite Quick Start Guides

Map Suite API Documentation

Map Suite FAQs

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
President ThinkGeo LLC
United States United States
Clint Batman is co-founder and President of ThinkGeo, a
software company specializing in geospatial software with an emphasis on software development tools and GPS tracking solutions.

Comments and Discussions

 
QuestionHow to do this without MapSuite Pin
SanShark21-Jun-08 3:55
SanShark21-Jun-08 3:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.