ZoomToBox() public method

Zooms the map to fit a bounding box
NOTE: If the aspect ratio of the box and the aspect ratio of the mapsize isn't the same, the resulting map-envelope will be adjusted so that it contains the bounding box, thus making the resulting envelope larger!
public ZoomToBox ( SharpMap bbox ) : void
bbox SharpMap
return void
Example #1
0
    public static Map CreateMap()
    {
      const string getCapabilitiesURI = "http://192.168.25.120:8080/deegree-wfs/services";

      Map map = new SharpMap.Map(new Size(600, 600));
      map.MinimumZoom = 0.005;
      map.BackColor = Color.White;

      SharpMap.Layers.VectorLayer layer1 = new SharpMap.Layers.VectorLayer("Springs");

      WFS prov1 = new WFS(getCapabilitiesURI, "app1", "Springs", WFS.WFSVersionEnum.WFS1_1_0);

      prov1.QuickGeometries = false;
      // Important when connecting to an UMN MapServer
      prov1.GetFeatureGETRequest = true;
      // Ignore multi-geometries...
      prov1.MultiGeometries = false;

      layer1.DataSource = prov1;
      map.Layers.Add(layer1);

      map.ZoomToBox(new SharpMap.Geometries.BoundingBox(574290, 4275299, 702273, 4386402));
      
      return map;
    }
Example #2
0
    public static SharpMap.Map InitializeGoogleMap(GoogleMapType mt)
    {
        SharpMap.Map map = new SharpMap.Map();

        GoogleRequest req;
        ITileSource tileSource;
        TileAsyncLayer tileLayer;

        if (mt == (GoogleMapType.GoogleSatellite | GoogleMapType.GoogleLabels))
        {
            req = new GoogleRequest(GoogleMapType.GoogleSatellite);
            tileSource = new GoogleTileSource(req);
            tileLayer = new TileAsyncLayer(tileSource, "TileLayer - " + GoogleMapType.GoogleSatellite);
            map.Layers.Add(tileLayer);
            req = new GoogleRequest(GoogleMapType.GoogleLabels);
            tileSource = new GoogleTileSource(req);
            mt = GoogleMapType.GoogleLabels;
        }
        else
        {
            req = new GoogleRequest(mt);
            tileSource = new GoogleTileSource(req);
        }

        tileLayer = new TileAsyncLayer(tileSource, "TileLayer - " + mt);
        map.BackgroundLayer.Add(tileLayer);
        map.ZoomToBox(tileLayer.Envelope);
        return map;
    }
Example #3
0
    public static SharpMap.Map InitializeGoogleMap(GoogleMapType mt)
    {
        SharpMap.Map map = new SharpMap.Map();

        GoogleRequest  req;
        ITileSource    tileSource;
        TileAsyncLayer tileLayer;

        if (mt == (GoogleMapType.GoogleSatellite | GoogleMapType.GoogleLabels))
        {
            req        = new GoogleRequest(GoogleMapType.GoogleSatellite);
            tileSource = new GoogleTileSource(req);
            tileLayer  = new TileAsyncLayer(tileSource, "TileLayer - " + GoogleMapType.GoogleSatellite);
            map.Layers.Add(tileLayer);
            req        = new GoogleRequest(GoogleMapType.GoogleLabels);
            tileSource = new GoogleTileSource(req);
            mt         = GoogleMapType.GoogleLabels;
        }
        else
        {
            req        = new GoogleRequest(mt);
            tileSource = new GoogleTileSource(req);
        }

        tileLayer = new TileAsyncLayer(tileSource, "TileLayer - " + mt);
        map.BackgroundLayer.Add(tileLayer);
        map.ZoomToBox(tileLayer.Envelope);
        return(map);
    }
Example #4
0
    public static Map InitializeMap()
    {
      const string getCapabilitiesURI = "http://steven:8080/eWaterWfsConnector/wfs";

      Map map = new SharpMap.Map(new System.Drawing.Size(600, 600));
      map.MinimumZoom = 0.005;
      map.BackColor = System.Drawing.Color.White;

      SharpMap.Layers.VectorLayer layer1 = new SharpMap.Layers.VectorLayer("test");
      
      WFS prov1 = new WFS(getCapabilitiesURI, "", "Well", WFS.WFSVersionEnum.WFS1_0_0);

      prov1.QuickGeometries = false;
      // Important when connecting to an UMN MapServer
      prov1.GetFeatureGETRequest = true;
      // Ignore multi-geometries...
      prov1.MultiGeometries = false;

      layer1.DataSource = prov1;
      map.Layers.Add(layer1);

      map.ZoomToBox(new SharpMap.Geometries.BoundingBox(574290, 4275299, 702273, 4386402));

      return map;
    }
Example #5
0
    public static Map CreateMap()
    {
      const string getCapabilitiesURI = "http://www2.dmsolutions.ca/cgi-bin/mswfs_gmap?request=GetCapabilities&service=WFS&VERSION=1.0.0";

      Map demoMap = new SharpMap.Map(new Size(600, 600));
      demoMap.MinimumZoom = 0.005;
      demoMap.BackColor = Color.White;

      SharpMap.Layers.VectorLayer layer1 = new SharpMap.Layers.VectorLayer("prov_land");
      WFS prov1 = new WFS(getCapabilitiesURI, "", "prov_land", WFS.WFSVersionEnum.WFS1_1_0);
      layer1.Style.Fill = new SolidBrush(Color.IndianRed);    // States
      //// Options 
      // Defaults: MultiGeometries: true, QuickGeometries: false, GetFeatureGETRequest: false
      // Render with validation...
      prov1.QuickGeometries = false;
      // Important when connecting to an UMN MapServer
      //!!!prov1.GetFeatureGETRequest = true;
      // Ignore multi-geometries...
      prov1.MultiGeometries = false;
      layer1.DataSource = prov1;
      demoMap.Layers.Add(layer1);

      demoMap.ZoomToBox(new SharpMap.Geometries.BoundingBox(-3546709.473205, -869773.355764, 4444893.074820, 3923457.184829));

      return demoMap;
    }
Example #6
0
        private static Map InitializeMapOsm()
        {
            Map map = new Map();

            TileLayer tileLayer = new TileLayer(new OsmTileSource(), "TileLayer - OSM");
            map.Layers.Add(tileLayer);
            map.ZoomToBox(tileLayer.Envelope);
            return map;
        }
Example #7
0
        public static Map InitializeMap()
        {
            Map map = new Map();

              string url = "http://labs.metacarta.com/wms-c/tilecache.py?version=1.1.1&request=GetCapabilities&service=wms-c";
              TiledWmsLayer tiledWmsLayer = new TiledWmsLayer("Metacarta", url);
              tiledWmsLayer.TileSetsActive.Add(tiledWmsLayer.TileSets["basic"].Name);
              map.Layers.Add(tiledWmsLayer);
              map.ZoomToBox(new SharpMap.Geometries.BoundingBox(-180.0, -90.0, 180.0, 90.0));

              return map;
        }
Example #8
0
        protected override void OnMouseWheel(MouseEventArgs e)
        {
            base.OnMouseWheel(e);

            if (_Map != null)
            {
                var rect = EnvelopeToRect(_Map.Envelope);

                System.Drawing.Point focus = new System.Drawing.Point(e.X, e.Y);

                double scale = (e.Delta < 0 ? 1.2 : 0.8);

                double newHeight = rect.Height * scale;
                double newWidth  = rect.Width * scale;

                double xx = focus.X - rect.X;
                double yy = focus.Y - rect.Y;

                double xratio = 0.5;
                double yratio = 0.5;

                if (rect.Contains(focus))
                {
                    xratio = (double)xx / (double)rect.Width;
                    yratio = (double)yy / (double)rect.Height;
                }

                int deltax = (int)((double)(rect.Width - newWidth) * xratio);
                int deltay = (int)((double)(rect.Height - newHeight) * yratio);

                double dx = rect.X + deltax;
                double dy = rect.Y + deltay;

                RectangleF  newrect = new RectangleF((float)dx, (float)dy, (float)newWidth, (float)newHeight);
                BoundingBox newEnv  = RectToEnvelope(newrect);
                _Map.ZoomToBox(newEnv);

                Refresh();
            }
        }
Example #9
0
        public void TestMap2()
        {
            var m = new Map(_mapSize);
            m.BackgroundLayer.Add(new TileLayer(new OsmTileSource(new OsmRequest(KnownOsmTileServers.MapQuest)), "MapQuest"));

            var codeBase = Path.GetDirectoryName(GetType().Assembly.CodeBase);
            var cn = string.Format("Data Source={0};",
                                   Path.Combine(new Uri(codeBase).LocalPath, "TestData", "osm_aurich.sqlite"));

            var ct = Wgs84ToWebMercator;
            //Env[7,45731445821406 : 7,53454260528903, 53,4342695512313 : 53,478793942147]
            var box = new Envelope(7.45731445821406, 7.53454260528903, 53.4342695512313, 53.478793942147);
            var box3857 = GeometryTransform.TransformBox(box, ct.MathTransform);

            m.ZoomToBox(box3857);

            foreach (var msp in ManagedSpatiaLite.GetSpatialTables(cn))
            {
                var l = new VectorLayer(msp.Table, msp);
                switch (msp.Table.Substring(0, 2).ToLower())
                {
                    case "pt":
                        l.Style = VectorStyle.CreateRandomPuntalStyle();
                        break;
                    case "ln":
                        l.Style = VectorStyle.CreateRandomLinealStyle();
                        break;
                    case "pg":
                        l.Style = VectorStyle.CreateRandomPolygonalStyle();
                        break;
                    default:
                        l.Style = VectorStyle.CreateRandomStyle();
                        break;
                }

                l.CoordinateTransformation = ct;
                m.Layers.Add(l);
            }

            var f = GetFormatter();
            BruTile.Utility.AddBruTileSurrogates(GetFormatter());

            Map mD = null;
            Assert.DoesNotThrow(() => mD = SandD(m, f));

            TestMaps("Test2", m, mD);
        }
Example #10
0
        public void TestRender()
        {
            var style = new SharpMap.Styles.GroupStyle();
             var vStyle = new SharpMap.Styles.VectorStyle()
             {
                 Enabled = true,
                 PointColor = Brushes.Red,
                 PointSize = 6
             };
             style.AddStyle(vStyle);

             vStyle = new SharpMap.Styles.VectorStyle()
             {
                 Enabled = true,
                 PointColor = Brushes.White,
                 PointSize = 2
             };
             style.AddStyle(vStyle);

             Assert.AreEqual(2, style.Count);
             Assert.AreEqual(Color.Red, (style[0].PointColor as SolidBrush).Color);

             VectorLayer vLay = new VectorLayer("test");
             vLay.Style = style;

             vLay.DataSource = new SharpMap.Data.Providers.GeometryProvider("POINT(0 0)");

             Map m = new Map(new Size(11, 11));
             m.BackColor = Color.White;
             m.ZoomToBox(new GeoAPI.Geometries.Envelope(-5, 5, -5, 5));
             m.Layers.Add(vLay);
             var img = m.GetMap();

             //img.Save(@"c:\\temp\ren.png");

             Bitmap bmp = img as Bitmap;
             Color c1 = bmp.GetPixel(5, 5);
             Assert.AreEqual(Color.White.ToArgb(), c1.ToArgb());
             c1 = bmp.GetPixel(3, 5);
             Assert.AreEqual(Color.Red.ToArgb(), c1.ToArgb());
             c1 = bmp.GetPixel(7, 5);
             Assert.AreEqual(Color.Red.ToArgb(), c1.ToArgb());
             c1 = bmp.GetPixel(5, 3);
             Assert.AreEqual(Color.Red.ToArgb(), c1.ToArgb());
             c1 = bmp.GetPixel(5, 7);
             Assert.AreEqual(Color.Red.ToArgb(), c1.ToArgb());
        }
        private Map InitMap()
        {
            var res = new SharpMap.Map()
            {
                SRID      = 3857,
                BackColor = System.Drawing.Color.AliceBlue,
            };

            //Lisbon...
            var mathTransform = LayerTools.Wgs84toGoogleMercator.MathTransform;
            var geom          = GeometryTransform.TransformBox(
                new Envelope(-9.205626, -9.123736, 38.690993, 38.740837),
                mathTransform);

            //geom.ExpandBy(2500);
            res.ZoomToBox(geom);

            res.Decorations.Add(new NorthArrow {
                ForeColor = Color.DarkSlateBlue
            });
            return(res);
        }
Example #12
0
        public void TestZoomToBoxRaisesMapViewOnChange()
        {
            var raised = false;
            var map = new Map(new Size(400, 200));
            map.MapViewOnChange += () => raised = true;

            // ZoomToBox
            map.ZoomToBox(new BoundingBox(20, 100, 10, 180));
            Assert.IsTrue(raised, "MapViewOnChange not fired when calling Map.ZoomToBox(...).");
            raised = false;
            map.ZoomToBox(new BoundingBox(20, 100, 10, 180));
            Assert.IsFalse(raised, "MapViewOnChange fired when calling Map.ZoomToBox(map.Envelope).");

            // ZoomToExtents
            // Note: Not needed as Map.ZoomToExtents() calls Map.ZoomToBox(Map.GetExtents())
            //raised = false;
            //map.ZoomToExtents();
            //Assert.IsTrue(raised, "MapViewOnChange not fired when calling Map.ZoomToExtents()");
            //raised = false;
            //map.ZoomToExtents();
            //Assert.IsFalse(raised, "MapViewOnChange fired when calling Map.ZoomToExtents() twice");

            // Set Zoom
            map.Zoom = map.Zoom * 0.9;
            Assert.IsTrue(raised, "MapViewOnChange not fired when setting Map.Zoom.");
            raised = false;
            map.Zoom = map.Zoom;
            Assert.IsFalse(raised, "MapViewOnChange not fired when setting Map.Zoom = Map.Zoom");

            // Set Center
            map.Center = new Coordinate(map.Center.X + 1, map.Center.Y);
            Assert.IsTrue(raised, "MapViewOnChange not fired when setting Map.Center.");
            raised = false;
            map.Center = map.Center;
            Assert.IsFalse(raised, "MapViewOnChange fired when setting Map.Center = Map.Center.");
        }
Example #13
0
        private static Map InitializeMapOsmWithXls(float angle)
        {
            Map map = new Map();

            TileLayer tileLayer = new TileLayer(new OsmTileSource(), "TileLayer - OSM with XLS");
            map.Layers.Add(tileLayer);

            //Get data from excel
            var xlsPath = string.Format(XlsConnectionString, System.IO.Directory.GetCurrentDirectory(), "GeoData\\Cities.xls");
            var ds = new System.Data.DataSet("XLS");
            using (var cn = new System.Data.OleDb.OleDbConnection(xlsPath))
            {
                cn.Open();
                using (var da = new System.Data.OleDb.OleDbDataAdapter(new System.Data.OleDb.OleDbCommand("SELECT * FROM [Cities$]", cn)))
                    da.Fill(ds);
            }

#if !DotSpatialProjections

            //The SRS for this datasource is EPSG:4326, therefore we need to transfrom it to OSM projection
            var ctf = new ProjNet.CoordinateSystems.Transformations.CoordinateTransformationFactory();
            var cf = new ProjNet.CoordinateSystems.CoordinateSystemFactory();
            var epsg4326 = cf.CreateFromWkt("GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]");
            var epsg3785 = cf.CreateFromWkt("PROJCS[\"Popular Visualisation CRS / Mercator\", GEOGCS[\"Popular Visualisation CRS\", DATUM[\"Popular Visualisation Datum\", SPHEROID[\"Popular Visualisation Sphere\", 6378137, 0, AUTHORITY[\"EPSG\",\"7059\"]], TOWGS84[0, 0, 0, 0, 0, 0, 0], AUTHORITY[\"EPSG\",\"6055\"]],PRIMEM[\"Greenwich\", 0, AUTHORITY[\"EPSG\", \"8901\"]], UNIT[\"degree\", 0.0174532925199433, AUTHORITY[\"EPSG\", \"9102\"]], AXIS[\"E\", EAST], AXIS[\"N\", NORTH], AUTHORITY[\"EPSG\",\"4055\"]], PROJECTION[\"Mercator\"], PARAMETER[\"False_Easting\", 0], PARAMETER[\"False_Northing\", 0], PARAMETER[\"Central_Meridian\", 0], PARAMETER[\"Latitude_of_origin\", 0], UNIT[\"metre\", 1, AUTHORITY[\"EPSG\", \"9001\"]], AXIS[\"East\", EAST], AXIS[\"North\", NORTH], AUTHORITY[\"EPSG\",\"3785\"]]");
            var ct = ctf.CreateFromCoordinateSystems(epsg4326, epsg3785);
            foreach (System.Data.DataRow row in ds.Tables[0].Rows)
            {
                if (row["X"] == DBNull.Value || row["Y"] == DBNull.Value) continue;
                double[] coords = new double[] { Convert.ToDouble(row["X"]), Convert.ToDouble(row["Y"])};
                coords = ct.MathTransform.Transform(coords);
                row["X"] = coords[0];
                row["Y"] = coords[1];
            }

#else
            var epsg4326 = DotSpatial.Projections.KnownCoordinateSystems.Geographic.World.WGS1984;
            var epsg3785 = new DotSpatial.Projections.ProjectionInfo();
            epsg3785.ReadEsriString("PROJCS[\"Popular Visualisation CRS / Mercator\", GEOGCS[\"Popular Visualisation CRS\", DATUM[\"Popular Visualisation Datum\", SPHEROID[\"Popular Visualisation Sphere\", 6378137, 0, AUTHORITY[\"EPSG\",\"7059\"]], TOWGS84[0, 0, 0, 0, 0, 0, 0], AUTHORITY[\"EPSG\",\"6055\"]],PRIMEM[\"Greenwich\", 0, AUTHORITY[\"EPSG\", \"8901\"]], UNIT[\"degree\", 0.0174532925199433, AUTHORITY[\"EPSG\", \"9102\"]], AXIS[\"E\", EAST], AXIS[\"N\", NORTH], AUTHORITY[\"EPSG\",\"4055\"]], PROJECTION[\"Mercator\"], PARAMETER[\"False_Easting\", 0], PARAMETER[\"False_Northing\", 0], PARAMETER[\"Central_Meridian\", 0], PARAMETER[\"Latitude_of_origin\", 0], UNIT[\"metre\", 1, AUTHORITY[\"EPSG\", \"9001\"]], AXIS[\"East\", EAST], AXIS[\"North\", NORTH], AUTHORITY[\"EPSG\",\"3785\"]]");
            foreach (System.Data.DataRow row in ds.Tables[0].Rows)
            {
                if (row["X"] == DBNull.Value || row["Y"] == DBNull.Value) continue;
                double[] coords = new double[] { Convert.ToDouble(row["X"]), Convert.ToDouble(row["Y"])};
                DotSpatial.Projections.Reproject.ReprojectPoints(coords, null, epsg4326, epsg3785, 0, 1);
                row["X"] = coords[0];
                row["Y"] = coords[1];
            }

#endif
            //Add Rotation Column
            ds.Tables[0].Columns.Add("Rotation", typeof (float));
            foreach (System.Data.DataRow row in ds.Tables[0].Rows)
                row["Rotation"] = -angle;

            //Set up provider
            var xlsProvider = new SharpMap.Data.Providers.DataTablePoint(ds.Tables[0], "OID", "X", "Y");
            var xlsLayer = new SharpMap.Layers.VectorLayer("XLS", xlsProvider);
            xlsLayer.Style.Symbol = SharpMap.Styles.VectorStyle.DefaultSymbol;
            
            //Add layer to map
            map.Layers.Add(xlsLayer);
            var xlsLabelLayer = new SharpMap.Layers.LabelLayer("XLSLabel");
            xlsLabelLayer.DataSource = xlsProvider;
            xlsLabelLayer.LabelColumn = "Name";
            xlsLabelLayer.PriorityColumn = "Population";
            xlsLabelLayer.Style.CollisionBuffer = new System.Drawing.SizeF(2f, 2f);
            xlsLabelLayer.Style.CollisionDetection = true;
            xlsLabelLayer.LabelFilter = SharpMap.Rendering.LabelCollisionDetection.ThoroughCollisionDetection;
            map.Layers.Add(xlsLabelLayer);

            map.ZoomToBox(tileLayer.Envelope);

            return map;
        }
Example #14
0
        private static Map InitializeMapGoogle(GoogleMapType mt)
        {
            Map map = new Map();

            GoogleRequest req;
            ITileSource tileSource;
            TileLayer tileLayer;
           
            if (mt == (GoogleMapType.GoogleSatellite | GoogleMapType.GoogleLabels))
            {
                req = new GoogleRequest(GoogleMapType.GoogleSatellite);
                tileSource = new GoogleTileSource(req);
                tileLayer = new TileLayer(tileSource, "TileLayer - " + GoogleMapType.GoogleSatellite);
                map.Layers.Add(tileLayer);
                req = new GoogleRequest(GoogleMapType.GoogleLabels);
                tileSource = new GoogleTileSource(req);
                mt = GoogleMapType.GoogleLabels;
            }
            else
            {
                req = new GoogleRequest(mt);
                tileSource = new GoogleTileSource(req);
            }

            tileLayer = new TileLayer(tileSource, "TileLayer - " + mt);
            map.Layers.Add(tileLayer);
            map.ZoomToBox(tileLayer.Envelope);
            return map;
        }
Example #15
0
        private static Map InitializeMapBing(BingMapType mt)
        {
            Map map = new Map();

            TileLayer tileLayer = new TileLayer(new BingTileSource(BingRequest.UrlBingStaging, "", mt) , "TileLayer - Bing " + mt);
            map.Layers.Add(tileLayer);
            map.ZoomToBox(tileLayer.Envelope);
            return map;
        }
Example #16
0
        private static Map InitializeMapOsmWithVariableLayerCollection(float angle)
        {
            Map map = new Map();

            TileLayer tileLayer = new TileLayer(new OsmTileSource(), "TileLayer - OSM with VLC");
            map.Layers.Add(tileLayer);

            VectorLayer vl = null;
            vl = new VectorLayer("Vilnius Transport Data - Bus", 
                new VilniusTransportData(VilniusTransportData.TransportType.Bus));
            PublicTransportTheme pttBus = new PublicTransportTheme(Brushes.DarkGreen);
            vl.Theme = new CustomTheme(pttBus.GetStyle);
            vl.CoordinateTransformation = GetCoordinateTransformation();
            map.VariableLayers.Add(vl);
            vl = new VectorLayer("Vilnius Transport Data - Trolley", 
                new VilniusTransportData(VilniusTransportData.TransportType.TrolleyBus));
            PublicTransportTheme pttTrolley = new PublicTransportTheme(Brushes.Red);
            vl.Theme = new CustomTheme(pttTrolley.GetStyle);
            vl.CoordinateTransformation = GetCoordinateTransformation();
            map.VariableLayers.Add(vl);
            VariableLayerCollection.Interval = 5000;

            map.ZoomToBox(vl.Envelope);

            return map;
        }
Example #17
0
 public void ZoomToBox_WithAspectCorrection()
 {
     Map map = new Map(new Size(400, 200));
     map.ZoomToBox(new BoundingBox(20, 10, 100, 180));
     Assert.AreEqual(new Point(60, 95), map.Center);
     Assert.AreEqual(340, map.Zoom);
 }
Example #18
0
 public void ZoomToBoxWithEnforcedMaximumExtents()
 {
     Map map = new Map();
     //map.MaximumZoom = 100;
     map.MaximumExtents = new Envelope(-180, 180, -90, 90);
     map.EnforceMaximumExtents = true;
     map.ZoomToBox(new Envelope(-200, 200, -100, 100));
     Assert.IsTrue(map.MaximumExtents.Contains(map.Envelope));
     Assert.AreEqual(new BoundingBox(-120, 120, -90, 90), map.Envelope);
 }
        public void ProcessRequest(HttpContext context)
        {
            // tile keys
            int x, y, z;

            //Parse request parameters
            if (!int.TryParse(context.Request.Params["x"], out x))
                throw (new ArgumentException("Invalid parameter"));
            if (!int.TryParse(context.Request.Params["y"], out y))
                throw (new ArgumentException("Invalid parameter"));
            if (!int.TryParse(context.Request.Params["z"], out z))
                throw (new ArgumentException("Invalid parameter"));
            string layer = context.Request.Params["layer"]; // not used here
            string style = context.Request.Params["style"]; // not used here

            // set response type to png
            context.Response.ContentType = "image/png";

            // check if already rendered, rendered tiles are cached within HttpContext
            string cacheKey = string.Format("Tile/{0}/{1}/{2}/{3}/{4}", layer, style, x, y, z);
            byte[] buffer = context.Cache[cacheKey] as byte[];
            if (buffer != null)
            {
                context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                return;
            }

            // create a transparent sharpmap map with a size of 256x256
            using (var sharpMap = new Map(new Size(256, 256)) { BackColor = Color.Transparent })
            {
                // the map contains only one layer
                var countries = new VectorLayer("WorldCountries")
                {
                    // set tranform to WGS84->Spherical_Mercator
                    CoordinateTransformation = TransformToMercator(GeographicCoordinateSystem.WGS84),

                    // set the sharpmap provider for shape files as data source
                    DataSource = new ShapeFile(
                        Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data") +
                        @"\world_countries_boundary_file_world_2002.shp"),

                    // use a dynamic style for thematic mapping
                    // the lambda also takes the map instance into account (to scale the border width)
                    Theme = new CustomTheme(row => GetPopDensStyle(sharpMap, row)),
                };

                // add the layer to the map
                sharpMap.Layers.Add(countries);

                // calculate the bbox for the tile key and zoom the map
                sharpMap.ZoomToBox(TileToMercatorAtZoom(x, y, z));

                // render the map image
                using (var img = sharpMap.GetMap())
                {
                    // stream the image to the client
                    using (var memoryStream = new MemoryStream())
                    {
                        // Saving a PNG image requires a seekable stream, first save to memory stream
                        // http://forums.asp.net/p/975883/3646110.aspx#1291641
                        img.Save(memoryStream, ImageFormat.Png);
                        buffer = memoryStream.ToArray();

                        // write response
                        context.Response.OutputStream.Write(buffer, 0, buffer.Length);

                        // add to cache
                        context.Cache[cacheKey] = buffer;
                    }
                }
            }
        }