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
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)
{
MapEngine mapServer = new MapEngine();
Layer stateLayer = new Layer(
this.Server.MapPath("") + @"\SampleData\STATES.shp");
GeoStyle stateGeoStyle = GeoAreaStyles.GetSimpleAreaStyle
(GeoColor.GeographicColors.State1, GeoColor.KnownColors.Black);
stateLayer.ZoomLevel01.GeoStyle = stateGeoStyle;
stateLayer.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.ZoomLevel18;
mapServer.Layers.Add(stateLayer);
Application.Add("mapServer", mapServer);
}
protected void Application_End(object sender, EventArgs e)
{
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
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
{
[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)
{
System.Threading.Monitor.Enter(Application["mapServer"]);
MapEngine map1;
map1 = Application["mapServer"] as MapEngine;
RectangleR fullExtent = new RectangleR(new PointR(uLX, uLY), new PointR(lRX,
lRY));
Bitmap bmp = new Bitmap(width, height);
Graphics g = Graphics.FromImage(bmp);
map1.GetMap(g, fullExtent, width, height, MapLengthUnits.DecimalDegrees, 0);
g.Dispose();
System.Threading.Monitor.Exit(Application["mapServer"]);
MemoryStream MemoryStream = new MemoryStream();
ImageCodecInfo[] icf = ImageCodecInfo.GetImageEncoders();
EncoderParameters encps = new EncoderParameters(1);
EncoderParameter encp = new EncoderParameter(Encoder.Quality, (long)quality);
encps.Param[0] = encp;
bmp.Save(MemoryStream, icf[1], encps);
MemoryStream.Close();
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
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)
{
Map1.MapUnit = MapSuite.Geometry.MapLengthUnits.DecimalDegrees;
Map1.AutoFullExtent = false;
Map1.CurrentExtent = new RectangleR(-125, 55, -66, 18);
Map1.Mode = MapSuite.WebEdition.Map.ModeType.Pan;
Map1.AjaxEnabled = true;
DisplayCustomerPoints();
}
}
protected void Map1_BeforeLayersDraw(System.Drawing.Graphics G)
{
localhost.MapService MapMaker = new localhost.MapService();
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);
MemoryStream MemoryStream = new MemoryStream(images);
Bitmap NewImage = new Bitmap(MemoryStream);
G.DrawImageUnscaled(NewImage, 0, 0);
}
protected void DisplayCustomerPoints()
{
DynamicLayer customers = new DynamicLayer();
PointMapShape custLA = new PointMapShape(new PointShape(-118.24, 34.05));
PointSymbol symLA = new PointSymbol
(new Bitmap(this.Server.MapPath("") + @"\images\customer.png"));
custLA.ZoomLevel01.GeoStyle.SymbolRenderers.Add(new SymbolRenderer(symLA));
custLA.ZoomLevel01.GeoTextStyle = GeoTextStyles.GetSimpleTextStyle
(null, "Arial", 9, GeoFontStyle.Bold, GeoColor.KnownColors.Black);
custLA.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.ZoomLevel18;
custLA.Name = "LA Customer";
customers.MapShapes.Add(custLA);
PointMapShape custKC = new PointMapShape(new PointShape(-94.62, 39.11));
PointSymbol symKC = new PointSymbol
(new Bitmap(this.Server.MapPath("") + @"\images\customermale.png"));
custKC.ZoomLevel01.GeoStyle.SymbolRenderers.Add(new SymbolRenderer(symKC));
custKC.ZoomLevel01.GeoTextStyle = GeoTextStyles.GetSimpleTextStyle
(null, "Arial", 9, GeoFontStyle.Bold, GeoColor.KnownColors.Black);
custKC.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.ZoomLevel18;
custKC.Name = "Kansas City Customer";
customers.MapShapes.Add(custKC);
Map1.DynamicLayers.Add(customers);
}
protected void btnZoomIn_Click(object sender, EventArgs e)
{
Map1.ZoomIn(20);
}
protected void btnZoomOut_Click(object sender, EventArgs e)
{
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:
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