User Tools

Site Tools


source_code_webapieditionsample_overlays.zip

Source Code WebAPIEditionSample Overlays.zip

Global.asax.cs

using System.Web.Http;
 
namespace ThinkGeo.MapSuite.Overlays
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801
 
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            WebApiConfig.Register(GlobalConfiguration.Configuration);
        }
    }
}

WebApiConfig.cs

using System.Web.Http;
 
namespace ThinkGeo.MapSuite.Overlays
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();
 
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
 
            config.EnsureInitialized();
        }
    }
}

OverlayController.cs

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using ThinkGeo.MapSuite.Core;
using ThinkGeo.MapSuite.WebApiEdition;
 
namespace ThinkGeo.MapSuite.Overlays
{
    [RoutePrefix("Overlays")]
    public class OverlayController : ApiController
    {
        private static readonly string baseDirectory;
        private static Collection<Layer> customLayers;
 
        static OverlayController()
        {
            baseDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data");
            InitializeCustomLayers();
        }
 
        /// <summary>
        /// Refresh WorldMapKitLayer with dynamic layers.
        /// </summary>
        [Route("WorldMapKit/{dynamicLayersNames}/{z}/{x}/{y}")]
        [HttpGet]
        public HttpResponseMessage LoadWorldMapKitLayer(string dynamicLayersNames, int z, int x, int y)
        {
            LayerOverlay layerOverlay = new LayerOverlay();
 
            AddDynamicLayersToLayerOverlay(layerOverlay, dynamicLayersNames);
 
            return DrawTileImage(layerOverlay, z, x, y);
        }
 
        /// <summary>
        /// Refresh OpenStreetMapLayer with dynamic layers.
        /// </summary>
        [Route("OpenStreetMap/{dynamicLayersNames}/{z}/{x}/{y}")]
        [HttpGet]
        public HttpResponseMessage LoadOpenStreetMapLayer(string dynamicLayersNames, int z, int x, int y)
        {
            LayerOverlay layerOverlay = new LayerOverlay();
            OpenStreetMapLayer openStreetMapLayer = new OpenStreetMapLayer();
            layerOverlay.Layers.Add(openStreetMapLayer);
 
            AddDynamicLayersToLayerOverlay(layerOverlay, dynamicLayersNames);
 
            return DrawTileImage(layerOverlay, z, x, y);
        }
 
        /// <summary>
        /// Refresh BingMaps with key and dynamic layers.
        /// </summary>
        [Route("BingMaps/{key}/{dynamicLayersNames}/{z}/{x}/{y}")]
        [HttpGet]
        public HttpResponseMessage LoadBingMapsLayer(string key, string dynamicLayersNames, int z, int x, int y)
        {
            LayerOverlay layerOverlay = new LayerOverlay();
 
            BingMapsLayer bingMapsLayer = new BingMapsLayer();
            bingMapsLayer.Name = "bingMapsAerialLayer";
            bingMapsLayer.MapType = BingMapsMapType.Road;
            bingMapsLayer.ApplicationId = key;
            layerOverlay.Layers.Add(bingMapsLayer);
 
            AddDynamicLayersToLayerOverlay(layerOverlay, dynamicLayersNames);
 
            return DrawTileImage(layerOverlay, z, x, y);
        }
 
        /// <summary>
        /// Refresh GoogleMaps with dynamic layers.
        /// </summary>
        [Route("GoogleMaps/{dynamicLayersNames}/{z}/{x}/{y}")]
        [HttpGet]
        public HttpResponseMessage LoadGoogleMapsLayer(string dynamicLayersNames, int z, int x, int y)
        {
            LayerOverlay layerOverlay = new LayerOverlay();
 
            GoogleMapsLayer googleMapsLayer = new GoogleMapsLayer();
            googleMapsLayer.MapType = GoogleMapsMapType.Satellite;
            layerOverlay.Layers.Add(googleMapsLayer);
 
            AddDynamicLayersToLayerOverlay(layerOverlay, dynamicLayersNames);
 
            return DrawTileImage(layerOverlay, z, x, y);
        }
 
        /// <summary>
        /// Validates key for BingMaps.
        /// </summary>
        [Route("BingMapsValidate")]
        [HttpPost]
        public bool ValidateBingMapsKey([FromBody] string postData)
        {
            bool updateSuc = true;
            try
            {
                Dictionary<string, string> parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(postData);
 
                ValidateBingMapsKeyStr(parameters);
            }
            catch (Exception ex)
            {
                updateSuc = false;
            }
            return updateSuc;
 
        }
 
        /// <summary>
        /// Draw the map and return the image back to client in an HttpResponseMessage. 
        /// </summary>
        private HttpResponseMessage DrawTileImage(LayerOverlay layerOverlay, int z, int x, int y)
        {
            using (Bitmap bitmap = new Bitmap(256, 256))
            {
                GdiPlusGeoCanvas geoCanvas = new GdiPlusGeoCanvas();
                RectangleShape boundingBox = WebApiExtentHelper.GetBoundingBoxForXyz(x, y, z, GeographyUnit.Meter);
                geoCanvas.BeginDrawing(bitmap, boundingBox, GeographyUnit.Meter);
                layerOverlay.Draw(geoCanvas);
                geoCanvas.EndDrawing();
 
                MemoryStream ms = new MemoryStream();
                bitmap.Save(ms, ImageFormat.Png);
 
                HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.OK);
                msg.Content = new ByteArrayContent(ms.ToArray());
                msg.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
 
                return msg;
            }
        }
 
        /// <summary>
        /// Initializes custom layers.
        /// </summary>
        private static void InitializeCustomLayers()
        {
            ManagedProj4Projection wgs84ToGoogleProjection = new ManagedProj4Projection();
            wgs84ToGoogleProjection.InternalProjectionParametersString = Proj4Projection.GetWgs84ParametersString(); //4326
            wgs84ToGoogleProjection.ExternalProjectionParametersString = Proj4Projection.GetGoogleMapParametersString(); //900913
            wgs84ToGoogleProjection.Open();
 
            customLayers = new Collection<Layer>();
            string shpFilePathName = string.Format(@"{0}\POIs\Schools.shp", baseDirectory);
            string schoolImage = string.Format(@"{0}\Images\school.png", baseDirectory);
            ShapeFileFeatureLayer schoolsLayer = new ShapeFileFeatureLayer(shpFilePathName);
            schoolsLayer.Name = "schoolLayer";
            schoolsLayer.Transparency = 200f;
            schoolsLayer.ZoomLevelSet.ZoomLevel10.DefaultPointStyle = new PointStyle(new GeoImage(schoolImage));
            schoolsLayer.ZoomLevelSet.ZoomLevel10.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
            schoolsLayer.FeatureSource.Projection = wgs84ToGoogleProjection;
            customLayers.Add(schoolsLayer);
        }
 
        /// <summary>
        /// Validates key for BingMaps.
        /// </summary>
        /// <param name="parameters">key string for bing map</param>
        private void ValidateBingMapsKeyStr(Dictionary<string, string> parameters)
        {
            string loginServiceTemplate = "http://dev.virtualearth.net/REST/v1/Imagery/Metadata/{0}?&incl=ImageryProviders&o=xml&key={1}";
            string loginServiceUri = string.Format(CultureInfo.InvariantCulture, loginServiceTemplate, BingMapsMapType.Road, parameters["keyStr"]);
 
            WebRequest request = WebRequest.Create(loginServiceUri);
            request.GetResponse();
        }
 
        /// <summary>
        /// Adds dynamic layers to LayerOverlay.
        /// </summary>
        /// <param name="layerOverlay">target LayerOverlay</param>
        /// <param name="dynamicLayersNames">dynamic layer names</param>
        private void AddDynamicLayersToLayerOverlay(LayerOverlay layerOverlay, string dynamicLayersNames)
        {
            List<string> dynamicLayersName = new List<string>(dynamicLayersNames.Split(','));
            foreach (var name in dynamicLayersName)
            {
                switch (name)
                {
                    case "CustomOverlay":
                        layerOverlay.Layers.Add(customLayers.Single(l => l.Name == "schoolLayer"));
                        break;
                }
            }
        }
    }
}

AssemblyInfo.cs

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
 
// General Information about an assembly is controlled through the following 
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Overlays")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Overlays")]
[assembly: AssemblyCopyright("Copyright ©  2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
 
// Setting ComVisible to false makes the types in this assembly not visible 
// to COM components.  If you need to access a type in this assembly from 
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
 
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9d9d03f8-b15b-4cd7-94f0-32437782a8bc")]
 
// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version 
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Revision and Build Numbers 
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Global.asax.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Routing;
 
namespace ThinkGeo.MapSuite.Overlays
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801
 
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            WebApiConfig.Register(GlobalConfiguration.Configuration);
        }
    }
}

WebApiConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
 
namespace ThinkGeo.MapSuite.Overlays
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();
 
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
 
            config.EnsureInitialized();
        }
    }
}

AssemblyInfo.cs

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
 
// General Information about an assembly is controlled through the following 
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Overlays")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Overlays")]
[assembly: AssemblyCopyright("Copyright ©  2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
 
// Setting ComVisible to false makes the types in this assembly not visible 
// to COM components.  If you need to access a type in this assembly from 
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
 
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8edc958e-049c-4932-9590-97303462170d")]
 
// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version 
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Revision and Build Numbers 
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
source_code_webapieditionsample_overlays.zip.txt · Last modified: 2015/11/16 09:47 by tgwikiupdate