User Tools

Site Tools


map_suite_webapi_edition_quick_start_guide

Map Suite WebAPI Edition Quick Start Guide

Note: The page was created before Map Suite 10. Map Suite 10.0 organized many classes into new namespaces and assemblies as well as had a few minor breaks in compatibility. The majority of previously built code should work without modification assuming the new namespaces are added. For guidance on upgrading your existing code, please check out MapSuite 10 Upgrade Guide.

The Map Suite WebAPI Edition illustrated QuickStart Guide will guide you through the process of creating a sample application and will help you become familiar with Map Suite. This edition of the QuickStart Guide supports Map Suite WebAPI Edition 9.0.0.0 and higher, and will show you how to create a ASP.NET WebAPI application using this product.

If you want to build a Web Forms application using the standard Map Suite Web Edition product, please see the Web Edition QuickStart Guide instead.

Welcome to Map Suite™ WebAPI Edition from ThinkGeo, a full-featured mapping control that makes it easy for any Microsoft .NET developer to add mapping functionality to a Microsoft .NET application quickly and efficiently. Using the intuitive object model, even developers inexperienced in geographic information systems (GIS) can create fully functional maps in minutes.

This guide will help you quickly get started building your own spatially aware applications. Like any new software, there will be some learning along the way.

How do we begin taking advantage of the power of Map Suite? The best way to learn is to make a sample application with it.

Before we get started, make sure you've installed the ThinkGeo Product Center and that you've either started an evaluation or activated a full license of Map Suite WebAPI Edition. By default, this will install the Map Suite WebAPI Edition 9.0 assemblies to C:\Program Files (x86)\ThinkGeo\Map Suite 9.0\Map Suite WebAPI.

Download the Sample

Setting up the Environment

Let's start by creating a new WebAPI application in Visual Studio.NET 2012 IDE named “HelloWorld” (see Figure 1). Set the Templates to “.NET Framework 4.5” for the project. In next wizard page, select the “Empty” template; this means that your sample project won't have any built-in pages or functionalities.

If you are using Visual Studio.NET 2010, you need to install VS2010 SP1, and then create an ASP.NET MVC Web Application.

This Quick Start Guide uses a WebAPI application as an example, so you will need to have the ASP.NET MVC framework installed in order to follow along. The MVC 4 framework can be downloaded from ASP.NET MVC 4 Tools Update.


Figure 1. Creating a new project in Visual Studio.NET 2012 IDE.

To take advantage of the Asp.NET WebAPI, please go to “Tools” > “Library Package Manager” > “Package Manager Console”, then input “Install-Package Microsoft.AspNet.WebApi -Pre” and press Enter to install the lasted assemblies.


Figure 2. Installing the WebAPI DLLs.

Map Suite WebAPI "Hello World" Sample

In this section, we'll use Map Suite WebAPI Edition to display a map that uses your own data.

To begin, in the Default.htm file, let's enter a few lines of code that will display a simple map. Next, we'll have a look at the data and the important objects we'll use.

Display a Simple map

The first step in creating our “Hello World” sample application is to add a html file named Default.htm and include code that similar to the example below.


Figure 3. Adding Default.htm.

<!DOCTYPE html>
<html>
<head>
    <title>Hello World</title>
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
</head>
<body>
    <div id="map" style="height: 800px; width: 1200px"></div>
</body>
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<script>
    var map = L.map('map', { zoomAnimation: false }).setView([[39.6948,|-96.8150]], 4);
 
    <nowiki>//</nowiki> add thinkgeo map
    L.tileLayer.wms('http://{s}.thinkgeo.com/CachedWMSServer/WmsServer.axd', {
        subdomains: [['worldmapkit1',|'worldmapkit2', 'worldmapkit3', 'worldmapkit4', 'worldmapkit5', 'worldmapkit6']],
        layers: 'OSMWorldMapKitLayer',
        format: 'image/png',
        styles: 'WorldMapKitDefaultStyle',
        version: '1.1.1',
        attribution: '<a href="http://thinkgeo.com/map-suite-developer-gis/world-map-kit-sdk/">ThinkGeo</a> | &copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors '
    }).addTo(map);
</script>
</html>

Now press F5 to build and run your application. It should look like this:


Figure 4. The basic map display.

Shapefiles

Map Suite WebAPI Edition supports multiple kinds of data sources including Shapefiles, TAB files, SQL Server 2008, PostgreSQL, Oracle, etc. Here we'll provide an introduction to Shapefiles, which we'll use in the next section of this Quick Start Guide.

Maps are generally made up of shapes like lines (representing roads), dots (for points of interest, such as cities and towns at small scales), and polygons (delineating parks, etc.). Shapefiles store the coordinates that are used to draw or render these shapes. Shapefiles have a .shp extension.

Shapefiles also come with two supplementary files that help Map Suite work with the data.

The first supplementary file is the .shx file. This file provides a simple index of the main Shapefile; it tells the Map Suite component when to start reading binary data and when to stop. It is much like a directory for reading the binary data, or a lookup mechanism.

The second supplementary file is the .dbf file. This file holds tabular data associated with the features in the main Shapefile. For example, a Shapefile might have the coordinates for drawing a road, while the .dbf file may tell you the name, length, and type of the road (county road, state road, interstate highway, etc.).

All three files need to reside in the same directory, but the Map Suite component only expects you to designate the name and file path of the main Shapefile. Next, when we discuss layers, you’ll start understanding a bit more about how maps are constructed in Map Suite using the shape data.

ShapeFileFeatureLayers

A ShapeFileFeatureLayer in a map correlates to a single Shapefile, such as a network of roads. Your feature layer will be superimposed on top of the base map. In fact, you can incorporate multiple feature layers in your web mapping application. Overlapping layers of different types features on a map, such as agricultural areas, rivers, and roads, is a powerful way to visualize and work with data.

You can think of layers much like actual terrain in the real world. The landscape could be considered a “base map”, with “layers” of roads and rivers superimposed on it. Keep in mind that overlapping layers may obscure the layers below. Be sure to add them in a logical order so they can be visualized correctly. For example, make sure your roads are displayed on top of rivers, creeks and streams, so bridges will be visible on the map. While the order of overlapping layers won't be editable at the client end, the display of individual layers may be turned on or off by the end user.

How do we create and add layers? The general rule is to start big. Add polygon layers representing large areas, such as country or regional boundaries, as a first, “bottom” layer. Next, you may want to add layers with lines representing rivers and roads. Add the smallest and most specific features last, as the top layer. These may include points for cities or places of interest. Again, keep in mind that logic will dictate what works best.

Styles

While Shapefiles provide the coordinates for shapes, styles define their appearance. You can specify the color of a country, the width of a road, the shape (triangle, circle, cross etc.) of a point, and so on.

Map Suite has many preset styles built in, including styles for roads, rivers, cities, countries, and other features. This makes it easy to create great looking maps without a lot of hassle.

PresetZoomLevels

Styles define the way we visually represent the data, while ZoomLevels define the situation in which we want to display them. ZoomLevels allow for different levels of detail at different scales. For example, we can display small towns when zoomed in close, and omit them when zoomed out to the country level, to avoid cluttering the map.

Map Suite offers the 20 most common scales, from ZoomLevel01 to ZoomLevel20, at which you may want to change your display. What is scale? Scale is a ratio between the distance represented on the map and the corresponding distance on the ground, when measured in the same units. If a road is 10,000 inches long in the real world and a map depicts this length as 1 inch on the screen, then we say the scale of this map is 1:10,000. Now let's say ZoomLevel02 uses a scale of 1:500 and ZoomLevel03 uses a scale of 1:1200. In this situation a map with a scale of 1:1000 will match ZoomLevel03 - the ZoomLevel with the closest scale.

PresetZoomLevels has a very useful property called ZoomLevel.ApplyUntilZoomLevel, which you can easily use to extend your ZoomLevels. Let's say you want a particular style to be visible at ZoomLevel03 through ZoomLevel10. To make that work, simply code as follows:

worldLayer.ZoomLevelSet.ZoomLevel03.DefaultAreaStyle = AreaStyles.Country1;
worldLayer.ZoomLevelSet.ZoomLevel03.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level10;

Map Suite WebAPI "Hello World"

Now let's look at the code needed to bring this concept to fruition.

We need to add two Map Suite files, “WebApiEdition.dll” and “MapSuiteCore.dll”, to the reference. Right-click on “References” in Solution Explorer and select “Add Reference…”, navigate to the C:\Program Files (x86)\ThinkGeo\Map Suite 9.0\Map Suite WebAPI\Current Version\Managed Assemblies folder, and select both “WebApiEdition.dll” and “MapSuiteCore.dll”.


Figure 5. Adding the references.

Our next step is to add our Shapefile layers to the map. For this example, we'll use a Shapefile containing worldwide country borders. We have one such Shapefile available to us:

  • Worldwide country borders (cntry02.shp)

(NOTE: The data used in this sample can be found in the attached sample above in the “\AppData” folder.)

Let's add a controller named “HelloWorldController”, like this:

Figure 6. Adding the "HelloWorldController".

Then add the following code to HelloWorldController:

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
using ThinkGeo.MapSuite.Core;
using ThinkGeo.MapSuite.WebApiEdition;
 
namespace HelloWorld.Controllers
{
    [RoutePrefix("HelloWorld")]
    public class HelloWorldController : ApiController
    {
        [Route("tile/{z}/{x}/{y}")]
        [HttpGet]
        public HttpResponseMessage GetTile(int z, int x, int y)
        {
            <nowiki>//</nowiki> We create a new Layer and pass the path to a Shapefile into its constructor.
            ShapeFileFeatureLayer worldLayer = new ShapeFileFeatureLayer(HttpContext.Current.Server.MapPath(@"~/App_Data/cntry02.shp"));
            ManagedProj4Projection proj4 = new ManagedProj4Projection();
            proj4.InternalProjectionParametersString = Proj4Projection.GetWgs84ParametersString();
            proj4.ExternalProjectionParametersString = Proj4Projection.GetSphericalMercatorParametersString();
            proj4.Open();
 
            worldLayer.FeatureSource.Projection = proj4;
 
            // Set the worldLayer to use a preset Style. Since AreaStyles.Country1 has a YellowGreen background and Black border, our worldLayer will have the same render style. 
            worldLayer.ZoomLevelSet.ZoomLevel01.DefaultAreaStyle = AreaStyles.Country1;
 
            // This setting will apply from ZoomLevel01 to ZoomLevel20, which means the map will be rendered in the same style, no matter how far we zoom in or out. 
 
            worldLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
 
            LayerOverlay layerOverlay = new LayerOverlay();
            layerOverlay.Layers.Add(worldLayer);
 
            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;
            }
        }
    }
}

So what has occurred here? We've created a layer and added it to the map, and the map has rendered it according to its default style parameters. We've also used ZoomLevel to display the map the way we want.

NOTE: It is important that the MapUnit property of a Map object be set using the GeographyUnit Enumeration. This is because the coordinates stored in a Shapefile can be in decimal degrees (a format of latitude and longitude), feet, meters, or another unit system, and our map has no way to know what the Shapefile's unit of measurement is until we tell it. This information is normally found somewhere in the Shapefile's documentation (also referred to as its metadata), or within its supplemental data file, as discussed in the section on Shapefiles. It may also come as a separate .txt, .xml, or .html file that begins with the same file name as the main Shapefile.

The attributes [RoutePrefix(“HelloWorld”)] and [Route(“tile/{z}/{x}/{y}”)] are for custom route, we can easily access it by '/HelloWorld/tile/{z}/{x}/{y}'. To make it work, we need to modify the WebApiConfig.cs, like this:

public static void Register(HttpConfiguration config)
{
     // Web API routes
     config.MapHttpAttributeRoutes();
 
     config.Routes.MapHttpRoute(
       name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
       defaults: new { id = RouteParameter.Optional }
     );
 
     config.EnsureInitialized();
}

Now that the server side is ready, let's support it adding the following code to the client side:

L.tileLayer('/HelloWorld/Tile/{z}/{x}/{y}').addTo(map);
</source>
 
After adding, it will look like as following:
 
<code javascript>
<script>
    var map = L.map('map', { zoomAnimation: false }).setView([[39.6948,|-96.8150]], 4);
 
    // add thinkgeo map
    L.tileLayer.wms('http://{s}.thinkgeo.com/CachedWMSServer/WmsServer.axd', {
        subdomains: [['worldmapkit1',|'worldmapkit2', 'worldmapkit3', 'worldmapkit4', 'worldmapkit5', 'worldmapkit6']],
        layers: 'OSMWorldMapKitLayer',
        format: 'image/png',
        styles: 'WorldMapKitDefaultStyle',
        version: '1.1.1',
        attribution: '<a href="http://thinkgeo.com/map-suite-developer-gis/world-map-kit-sdk/">ThinkGeo</a> | &copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors '
    }).addTo(map);
 
    L.tileLayer('/HelloWorld/Tile/{z}/{x}/{y}').addTo(map);
</script>

If you compile and run what you have now, your map should look like the screenshot below. (See Figure 7).


Figure 7. A simple map of the world.

Now you can display and navigate your map. Pan by dragging the map, zoom in by double-clicking, track zoom in by drawing a rectangle with your left mouse button mouse while holding the shift key, or zoom in and out with the mouse wheel. Very powerful for just couple lines of code, isn't it?

That was an easy start! Now let's add a second Shapefile to the sample, so we'll have a total of two layers:

  1. World country borders (“cntry02.shp”)
  2. World capitals (“capital.shp”)

Change the code in server side to correspond with the following example. You don't need to make any changes to client side.

[Route("tile/{z}/{x}/{y}")]
[HttpGet]
public HttpResponseMessage GetTile(int z, int x, int y)
{
    // We create a new Layer and pass the path to a Shapefile into its constructor.
    ShapeFileFeatureLayer worldLayer = new ShapeFileFeatureLayer(HttpContext.Current.Server.MapPath(@"~/App_Data/cntry02.shp"));
    ManagedProj4Projection proj4 = new ManagedProj4Projection();
    proj4.InternalProjectionParametersString = Proj4Projection.GetWgs84ParametersString();
    proj4.ExternalProjectionParametersString = Proj4Projection.GetSphericalMercatorParametersString();
    proj4.Open();
 
    worldLayer.FeatureSource.Projection = proj4;
 
    // Set the worldLayer to use a preset style. Since AreaStyles.Country1 has a YellowGreen background and Black border, our worldLayer will have the   
    //same render style. 
    worldLayer.ZoomLevelSet.ZoomLevel01.DefaultAreaStyle = AreaStyles.Country1;
 
    // This setting will apply to all zoom levels from ZoomLevel01 through ZoomLevel20, so the same style will be rendered no matter how far we zoom in or out.
    worldLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
 
    // Capital layer
    ShapeFileFeatureLayer capitalLayer = new ShapeFileFeatureLayer(HttpContext.Current.Server.MapPath("~/App_Data/capital.shp"));
    capitalLayer.FeatureSource.Projection = proj4;
    capitalLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle = PointStyles.Capital3;
    capitalLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
 
    LayerOverlay layerOverlay = new LayerOverlay();
    layerOverlay.Layers.Add(worldLayer);
    layerOverlay.Layers.Add(capitalLayer);
 
    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;
    }
}

The result is as follows (Figure 8):


Figure 8. A basic map of the Americas with the additional borders and capitals layers displayed.

How to Use TextStyle

TextStyle is used to label items on map. While the features themselves are drawn from information in the Shapefile, they're labeled with feature names or other attributes contained in the .dbf file. For example, the Shapefile containing capitals of the world has a corresponding .dbf file with the field “CITY_NAME”. We can use this field to label the cities on our map.

qsg_webedition2_img11.jpg
Figure 9. Attribute data from the .dbf file.

Map Suite includes several built-in TextStyles to help us quickly apply attractive city labels. We can simply pick the TextStyle we like and use it.

[Route("tile/{z}/{x}/{y}")]
[HttpGet]
public HttpResponseMessage GetTile(int z, int x, int y)
{
    // We create a new Layer and pass the path to a Shapefile into its constructor.
    ShapeFileFeatureLayer worldLayer = new ShapeFileFeatureLayer(HttpContext.Current.Server.MapPath(@"~/App_Data/cntry02.shp"));
    ManagedProj4Projection proj4 = new ManagedProj4Projection();
    proj4.InternalProjectionParametersString = Proj4Projection.GetWgs84ParametersString();
    proj4.ExternalProjectionParametersString = Proj4Projection.GetSphericalMercatorParametersString();
    proj4.Open();
 
    worldLayer.FeatureSource.Projection = proj4;
 
    // Set the worldLayer to use a preset style. Since AreaStyles.Country1 has a YellowGreen background and Black border, our worldLayer will have the same render style. 
    worldLayer.ZoomLevelSet.ZoomLevel01.DefaultAreaStyle = AreaStyles.Country1;
 
    // This setting will apply from ZoomLevel01 to ZoomLevel20, which means the map will be rendered in the same style, no matter how far we zoom in or out. 
    worldLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
 
    // Capital layer
    ShapeFileFeatureLayer capitalLayer = new ShapeFileFeatureLayer(HttpContext.Current.Server.MapPath("~/App_Data/capital.shp"));
    capitalLayer.FeatureSource.Projection = proj4;
    capitalLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle = PointStyles.Capital3;
    capitalLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
 
    // Label layer
    ShapeFileFeatureLayer capitalLabelLayer = new ShapeFileFeatureLayer(HttpContext.Current.Server.MapPath("~/App_Data/capital.shp"));
    capitalLabelLayer.FeatureSource.Projection = proj4;
    // We'll use a preset TextStyle. Here we pass in "CITY_NAME", the name of the field containing the values we want to label the map with.
    capitalLabelLayer.ZoomLevelSet.ZoomLevel01.DefaultTextStyle = TextStyles.Capital3("CITY_NAME");
    capitalLabelLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
    // Since the map is drawn with tiles, the label needs to draw on the margin to make sure the text is complete after joining the tiles together.
    // Change the number below (to 0, for example) to better understand how this works.
    capitalLabelLayer.DrawingMarginPercentage = 50;
 
    LayerOverlay layerOverlay = new LayerOverlay();
    layerOverlay.Layers.Add(worldLayer);
    layerOverlay.Layers.Add(capitalLayer);
    layerOverlay.Layers.Add(capitalLabelLayer);
 
    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;
    }
}

The result is as follows (Figure 10):


Figure 10. Map of the Americas with TextStyle applied.

Now that we know how to render text and symbols, let's create custom Styles and TextStyles. We'll also specify different ranges of ZoomLevels, and apply varying custom Styles and TextStyles to the same layer at different ZoomLevel ranges.

[Route("tile/{z}/{x}/{y}")]
[HttpGet]
public HttpResponseMessage GetTile(int z, int x, int y)
{
    // Create a new Layer and pass the path to a Shapefile into its constructor.
    ShapeFileFeatureLayer worldLayer = new ShapeFileFeatureLayer(HttpContext.Current.Server.MapPath(@"~/App_Data/cntry02.shp"));
    ManagedProj4Projection proj4 = new ManagedProj4Projection();
    proj4.InternalProjectionParametersString = Proj4Projection.GetWgs84ParametersString();
    proj4.ExternalProjectionParametersString = Proj4Projection.GetSphericalMercatorParametersString();
    proj4.Open();
 
    worldLayer.FeatureSource.Projection = proj4;
 
    // Set the worldLayer to use a preset Style. Since AreaStyles.Country1 has a YellowGreen background and Black border, our worldLayer will have the same render style. 
    worldLayer.ZoomLevelSet.ZoomLevel01.DefaultAreaStyle = AreaStyles.Country1;
 
    // This setting will apply from ZoomLevel01 to ZoomLevel20, which means the map will be rendered in the same style, no matter how far we zoom in or out. 
    worldLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
 
    // Capital layer
    ShapeFileFeatureLayer capitalLayer = new ShapeFileFeatureLayer(HttpContext.Current.Server.MapPath("~/App_Data/capital.shp"));
    capitalLayer.FeatureSource.Projection = proj4;
    // We can customize our own Style. Here we pass in a color and a size.
    capitalLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle = PointStyles.CreateSimpleCircleStyle(GeoColor.StandardColors.White, 7, GeoColor.StandardColors.Brown);
    // The Style we set here is applied from ZoomLevel01 to ZoomLevel05. That means if we zoom in a bit more, this particular style will no longer be visible.
    capitalLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level05;
 
    capitalLayer.ZoomLevelSet.ZoomLevel06.DefaultPointStyle = PointStyles.Capital3;
    // The Style we set here is applied from ZoomLevel06 to ZoomLevel20. That means if we zoom out a bit more, this particular style will no longer be visible.
    capitalLayer.ZoomLevelSet.ZoomLevel06.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
 
    // Label layer
    ShapeFileFeatureLayer capitalLabelLayer = new ShapeFileFeatureLayer(HttpContext.Current.Server.MapPath("~/App_Data/capital.shp"));
    capitalLabelLayer.FeatureSource.Projection = proj4;
    // We can customize our own TextStyle. Here we pass in the font, the size, the style and the color.
    capitalLabelLayer.ZoomLevelSet.ZoomLevel01.DefaultTextStyle = TextStyles.CreateSimpleTextStyle("CITY_NAME", "Arial", 8, DrawingFontStyles.Italic, GeoColor.StandardColors.Black, 3, 3);
    // The TextStyle we set here is applied from ZoomLevel01 to ZoomLevel05. 
    capitalLabelLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level05;
 
    capitalLabelLayer.ZoomLevelSet.ZoomLevel06.DefaultTextStyle = TextStyles.Capital3("CITY_NAME");
    // The TextStyle we set here is applied from ZoomLevel06 to ZoomLevel20.
    capitalLabelLayer.ZoomLevelSet.ZoomLevel06.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
    // Change the number below (to 0, for example) to better understand how this works.
    capitalLabelLayer.DrawingMarginPercentage = 50;
 
    LayerOverlay layerOverlay = new LayerOverlay();
    layerOverlay.Layers.Add(worldLayer);
    layerOverlay.Layers.Add(capitalLayer);
    layerOverlay.Layers.Add(capitalLabelLayer);
 
    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;
    }
}

Can you imagine what the map will look like now? Figure 11 below is the result. At first it looks the same as it did in Figure 10. Now zoom in, and watch the map change to resemble Figure 12.


Figure 11. European cities with two ZoomLevels, before zooming in.


Figure 12. European cities with two ZoomLevels, after zooming in.

Perform an AJAX HTTP request to the Action of the Controller

Map Suite WebAPI Edition provides a large number of client APIs that allow us to easily operate the map on client side, just as we've done on the server side in the above sample code.

Here we'll show you how to perform an AJAX request to update the layers of the map according to the different parameters passed in from the client.

We will need to access the parameters passed from here in the action.

The code in your client side should look like this:

<!DOCTYPE html>
<html>
<head>
    <title>Hello World</title>
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
</head>
<body>
    <div id="map" style="height: 800px; width: 1200px"></div>
    <div>
        <input id="chKAddStates" name="group1" type="radio" value="Show US States" onclick="updateLayer('usstates')" />
        Show US States
    <br />
        <input id="chKAddCites" name="group1" type="radio" value="Show US Counties" onclick="updateLayer('uscities')" />
        Show US Cities
    <br />
    </div>
</body>
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<script>
    var map = L.map('map', { zoomAnimation: false }).setView([[39.6948,|-96.8150]], 4);
 
    // add thinkgeo map
    L.tileLayer.wms('http://{s}.thinkgeo.com/CachedWMSServer/WmsServer.axd', {
        subdomains: [['worldmapkit1',|'worldmapkit2', 'worldmapkit3', 'worldmapkit4', 'worldmapkit5', 'worldmapkit6']],
        layers: 'OSMWorldMapKitLayer',
        format: 'image/png',
        styles: 'WorldMapKitDefaultStyle',
        version: '1.1.1',
        attribution: '<a href="http://thinkgeo.com/map-suite-developer-gis/world-map-kit-sdk/">ThinkGeo</a> | &copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors '
    }).addTo(map);
 
    var worldLayer = L.tileLayer('/HelloWorld/Tile<nowiki>//</nowiki>{z}/{x}/{y}').addTo(map);
 
    function updateLayer(layerId) {
        worldLayer.setUrl('/HelloWorld/Tile/' + layerId + '/{z}/{x}/{y}');
        worldLayer.redraw();
    }
</script>
</html>

Now copy and paste the code below about the accessed action into your “HelloWorldController” page:

[Route("tile/{layerId}/{z}/{x}/{y}")]
[HttpGet]
public HttpResponseMessage GetTile(string layerId, int z, int x, int y)
{
    ManagedProj4Projection proj4 = new ManagedProj4Projection();
    proj4.InternalProjectionParametersString = Proj4Projection.GetWgs84ParametersString();
    proj4.ExternalProjectionParametersString = Proj4Projection.GetSphericalMercatorParametersString();
    proj4.Open();
 
    LayerOverlay layerOverlay = new LayerOverlay();
 
    if (layerId.ToLowerInvariant() == "usstates")
    {
        // States layer
        ShapeFileFeatureLayer statesLayer = new ShapeFileFeatureLayer(HttpContext.Current.Server.MapPath("~/App_Data/USStates.shp"));
        statesLayer.FeatureSource.Projection = proj4;
        statesLayer.ZoomLevelSet.ZoomLevel01.DefaultAreaStyle = AreaStyles.State1;
        statesLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
 
        layerOverlay.Layers.Add(statesLayer);
    }
    else if (layerId.ToLowerInvariant() == "uscities")
    {
        // Cities layer
        ShapeFileFeatureLayer countyLayer = new ShapeFileFeatureLayer(HttpContext.Current.Server.MapPath("~/App_Data/cities_a.shp"));
        countyLayer.FeatureSource.Projection = proj4;
        countyLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle = PointStyles.Capital3;
        countyLayer.ZoomLevelSet.ZoomLevel01.DefaultTextStyle = TextStyles.Capital3("AREANAME");
        countyLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
        layerOverlay.Layers.Add(countyLayer);
    }
 
    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;
    }
}

If we compile and run the application now, it should look like the screenshot below:


Figure 13. Note the client side layer display control that now appears below the map.

You can click the check boxes for “Show US States” or “Show US Cities” to load different layers to the map. For example, if you check the “Show US States” box, the map should look like this:


Figure 14. Map with states layer shown.

if you check the “Show US Cities” box, the map should look like this:


Figure 15. Map with cities layer shown.

Summary

You now know the basics of using Map Suite WebAPI Edition and can start adding this functionality to your own applications. Let's recap what we've learned about the object relationships and how the pieces of Map Suite work together:

  1. It is of the utmost importance that the units (feet, meters, decimal degrees, etc.) be set properly for the Map control, based on the requirements of your data.
  2. Shapefiles provide the data used by a Map control to render a map.
  3. A Layer can have one-to-many ZoomLevels. ZoomLevels help to define ranges (upper and lower scales) of when a Layer should be shown or hidden.

Download Sample Code From This Exercise (12.5 MB)

map_suite_webapi_edition_quick_start_guide.txt · Last modified: 2017/03/17 04:59 by tgwikiupdate