Blue Theme Orange Theme Green Theme Red Theme
 
Dundas Dashboard
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
World Class ASP.NET Hosting - 3 Month Free Hosting, Click Here!
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Web Services » Building Scalable Mapping and GIS Apps with Web Services

Building Scalable Mapping and GIS Apps with Web Services

This article will show you how to build a scalable mapping application utilizing a web service and also how to consume the web service from a client application.

Technologies: .NET 1.0/1.1, ASP.NET 1.0, Web Services,Visual C# .NET
Total downloads :
Total page views :  4499
Rating :
 0/5
This article has been rated :  0 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
Become a Sponsor


Related EbooksTop Videos

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)

        { 

            //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:

  1. uLX - upper left x coordinate of the map image requested
  2. uLY - upper left y coordinate of the map image requested
  3. lRX - lower right x coordinate of the map image requested
  4. lRY - lower right y coordinate of the map image requested
  5. height - height of image requested
  6. width - width of the image requested
  7. 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

{

    /// <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:

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:



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 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.

Additional Resources

Map Suite Quick Start Guides
Map Suite API Documentation
Map Suite FAQs


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Clint Batman
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.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Powerful ASP.NET Hosting w/ NO Setup Fees. Click Here!
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved