65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 Web 服务构建可扩展的映射和 GIS 应用程序

2008年2月14日

CPOL

7分钟阅读

viewsIcon

50885

如今,程序员需要对地图数据、地图渲染、GIS 功能、安全性和整体架构有更多的控制。本文将向您展示如何利用 Web 服务构建可扩展的地图应用程序,以及如何从客户端应用程序中获取 Web 服务。

引言

随着近年来流行在线地图应用程序的出现,越来越多的企业看到了在自有定制应用程序中构建地图和 GIS(地理信息系统)功能的需求。虽然 Google Maps 和 Virtual Earth 等在线服务在某些情况下效果很好,但很多时候程序员需要对地图数据、地图渲染、GIS 功能、安全性和整体架构有更多的控制。在本文中,我将向您展示如何利用 Web 服务构建可扩展的地图应用程序,以及如何从客户端应用程序中获取 Web 服务。

入门

通常,当我准备构建一个新的地图应用程序时,我会查看该应用程序将如何使用,并尝试将地图数据分为两类:

  • 底图 – 底图由您始终希望显示的相对静态的地图数据组成。通常,这些底图由常见的要素组成,例如政治边界、水体、道路和兴趣点。在本示例中,我将底图保持得非常简单,只使用美国轮廓图。如果我想使用更详细的底图,我将利用 Map Suite Data Plugins 来处理地图数据和渲染逻辑。
  • 动态地图数据 – 这种类型的地图数据经常变化,需要定期更新。通常,这种类型的数据存储在由应用程序或其他外部源更新的数据库中。在本示例中,我将再次保持简单,模拟绘制美国境内两个客户的位置。

现在我们对将要处理的两种不同类型的地图数据有了一个概念,我们可以开始构建将提供底图的 Web 服务了。

Web 服务

此 Web 服务需要实现的主要目标是提供一种高性能、可扩展的方式来渲染底图。这些底图将由我们的示例应用程序使用。将渲染底图的逻辑封装到 Web 服务中为我们带来了几个优势。这包括集中的地图数据存储、地图数据只加载到内存一次供所有用户使用,最后,您可以通过负载均衡器轻松扩展 Web 服务以应对不断增长的需求。

为实现最佳性能,我们将利用 Map Suite Engine Edition .NET 组件。该组件将负责处理渲染由我们示例应用程序使用的地图图像的繁重工作。要开始,您需要在 Visual Studio 2005 中创建一个新的 ASP.NET Web 服务项目。项目加载后,您需要做的第一件事是编写 Web 服务初始化代码。为此,您需要在 Web 服务中添加一个 Global.asax 文件。下面的 Global.asax 代码是实例化 MapEngine 对象并加载地图数据以便所有 Web 服务请求都可以使用的地方。

Global.asax 代码

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();
        }
    }
}

现在我们已经编写了初始化 Web 服务的代码,下一步是创建一个 WebMethod,我们的客户端应用程序可以调用该方法来检索地图图像。为此,您需要在解决方案中添加一个具有 .asmx 扩展名的新 Web 服务页面。在本示例中,我将 Web 服务页面命名为 MapService.asmx,并公开了一个名为 GetMapImage 的公共 WebMethodGetMapImage 方法接收一些参数,以便我们可以为正在使用的应用程序创建正确的地图图像。这些参数包括:

  • uLX - 请求的地图图像的左上角 x 坐标
  • uLY – 请求的地图图像的左上角 y 坐标
  • lRX – 请求的地图图像的右下角 x 坐标
  • lRY – 请求的地图图像的右下角 y 坐标
  • height – 请求的图像的高度
  • width – 请求的图像的宽度
  • quality – 返回的压缩图像的质量

有了这些参数,我们就可以利用在 global.asax 文件中初始化的地图引擎对象,在我们的 Web 服务中创建指定的地图图像。要了解如何实现这一点,请参阅以下代码:

MapService.asmx 代码

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();
        }
    }
}

客户端应用程序

现在我们已经构建了 Web 服务,接下来我们将重点转向将使用 Web 服务并绘制客户位置的客户端应用程序。在本示例中,我们将使用 Map Suite Web ASP.NET 服务器控件 构建一个 ASP.NET Web 应用程序;但是,同样可以轻松地在桌面客户端应用程序中使用 Map Suite Desktop .NET 控件 来获取 Web 服务。

要开始,您需要在 Visual Studio 2005 中创建一个新的 ASP.NET Web 应用程序。接下来,您需要引用 Map Suite Web Edition .NET Control 并将其拖到网页上。此外,别忘了将 HTTP Handler 部分添加到您的 web.config 文件中,以便地图控件能够正确渲染。最后,您需要将一个 Web 引用添加到之前创建的 Web 服务中。

一旦您的应用程序准备好开始编码,您将需要在 Page_Load 事件处理程序和 Map_BeforeLayerDraw 事件处理程序中编写一些代码,以及一些额外的代码来显示客户点并处理缩放。Page_Load 事件处理程序代码完成了几个任务。首先,它设置 MapUnit 属性,该属性告诉地图控件使用哪个坐标系。在本示例中,我们将使用的坐标系是十进制度,也称为经纬度坐标。接下来,我们编写一些代码来设置初始缩放级别并默认地图为平移模式。最后,Page_Load 中的最后一段代码调用 DisplayCustomerPoints 函数,该函数负责在地图上显示我们的动态客户点。

您可能会问,Web 服务在哪里发挥作用?通过在 Map_BeforeLayersDraw 事件处理程序中编写一些代码,我们将能够调用 Web 服务并在地图控件上绘制美国底图。为此,我们必须先实例化 Web 服务并调用 GetMapImage Web 方法。一旦我们从 Web 服务接收到包含地图图像的字节数组,最后的任务就是使用传递到事件处理程序的图形对象在地图控件上绘制地图图像。

为了使应用程序对用户更加友好,我添加了“放大”和“缩小”按钮,以便用户可以放大和缩小。要查看此代码以及上述所有代码,请参阅以下内容:

Default.aspx 代码

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);
    }
}

完成所有这些编码后,您应该能够运行您的客户端应用程序并获得类似于下图的屏幕截图:

image001.jpg

摘要

利用 Web 服务可以帮助您构建极其可扩展的地图和 GIS 解决方案。通过在 Web 服务中利用 Map Suite Engine .NET Component,您可以集中管理所有底图生成和大型地图数据集。此外,您仍然可以享受使用 Map Suite ASP.NET 和桌面控件 来处理所有用户交互和动态地图数据的显示等功能。本文仅仅触及了地图和 GIS Web 服务与丰富用户界面结合所能实现的皮毛。可下载的代码可以作为构建您自己的可扩展 .NET GIS 地图应用程序的良好起点。

下载次数

C# 中的地图 Web 服务和客户端示例代码

Map Suite Engine .NET Component 和 Web ASP.NET Control (需要注册)

注意:您需要下载并安装这些 Map Suite 组件才能运行本文中的示例。

有疑问吗?

您对本文有任何疑问或评论吗?欢迎在 Map Suite 讨论论坛上提问,或在 ThinkGeo Blog 上留下反馈。

额外资源

Map Suite 快速入门指南

Map Suite API 文档

Map Suite FAQ

© . All rights reserved.