# dotMorten

### .NET Ramblings, XAML hacking and some GIS endeavors

One of the things that SharpMap at the current stage lacks most is probably a relation model, making for instance intersectiontests possible (unless you use the PostGIS provider which uses its built-in relation model). This is important to be able to select features within a certain distance, which features intersects the point that was clicked on the map or features that intersect other features. At the current stage most intersection-tests are only done on bounding-box level, which - although very fast - isn't very precise.

NetTopologySuite is another great .NET library that among other does a lot of the things that SharpMap not (yet) can do. Fortunately Diego from the NTS team has made a link between NTS and SharpMap making this possible. They have posted an example on the NTS website showing how to check for exact intersection in SharpMap. Check it out. It is very cool and very powerful.

Charlie Savage has a great post introducing coordinate systems in his blog. I too have had many questions on coordinate systems, projections and datums, and Charlie have made a great introduction to the world of "spatial reference systems". He promises to post some more on the topic, so keep track of his blog if you find these topics confusing (I know I did when I first was told about datums and coordinate systems).

Here is a small C# method for calculating distances between two longitude/latitude points based on Movable Type's article on the subject. Since the earth isn't perfectly round, and since I've found several values for the approximate radius of the earth, this method is only approximate, but should be sufficiently accurate for most applications.

```/// <summary>
/// Calculates the distance between to lat/long points and returns the approximate distance in kilometers
/// </summary>
/// <param name="from">Point in long/lat decimal degrees</param>
/// <param name="to">Point in long/lat decimal degrees</param>
/// <returns>Distance in kilometers</returns>
private double CalcDistance(Point from, Point to)
{
double p1X = from.X / 180 * Math.PI;
double p1Y = from.Y / 180 * Math.PI;
double p2X = to.X / 180 * Math.PI;
double p2Y = to.Y / 180 * Math.PI;

return Math.Acos(Math.Sin(p1Y) * Math.Sin(p2Y) +
Math.Cos(p1Y) * Math.Cos(p2Y) * Math.Cos(p2X - p1X)) * rad;
}```

If you want the distance returned in something else than kilometers, change the radius to whatever unit you would like the output unit to be in.

I have successfully incorporated this in a SharpMap-based application for doing nearest-object searches in a map. It is fun to see how the earth-curvate is taken into account; -this is particularily visible towards the poles in a flat projected map.

Since Google Earth is so popular, I thought why not join in and have SharpMap serve maps for GE? It is quite simple to make your own GE Network Link, and here are a few pointers, and you can download a demo web application you can use as well.

The GE Network Link basically works by requesting an XML webpage (well Google calls it KML), telling GE where to get the image tiles and where they should be placed on the globe. GE also adds a 'BBOX=minx,miny,maxx,maxy' querystring to the request so you can return a custom KML response containing the most appropriate tile(s). A response could look like this:

<?xml version="1.0" encoding="UTF-8" ?>
<kml xmlns="
<Document>
<open>1</open>
<GroundOverlay>
<open>1</open>
<Icon>
<href>http://localhost/TileServer.ashx?BBOX=-180,-90,0,90&size=512</href>
</Icon>
<LatLonBox>
<north>90</north>
<south>-90</south>
<east>0</east>
<west>-180</west>
<rotation>0</rotation>
</LatLonBox>
</GroundOverlay>
</Document>
</kml>

You can add as many "GroundOverlays" as you like. For instance you can cover a requested BBOX with as many tiles as you like. That way you can increase the image size/resolution or cover a larger or smaller area than initially requested while getting quicker responses. You can read more about the KML format here.

Creating the KML is pretty straight-forward in ASP.NET, so I wont cover that here (but download the example and see for yourself).

Creating the image tile is easily done using SharpMap. Add an HttpHandler to you webpage, and create the following ProcessRequest method to render and return the map:

public void ProcessRequest(HttpContext context)

{

//Get tilesize in request url

int tilesize = int.Parse(context.Request.QueryString["size"]);

//Get boundingbox requested

string[] strbox = context.Request.QueryString["BBOX"].Split(new char[] { ',' });

SharpMap.Geometries.BoundingBox box = new SharpMap.Geometries.BoundingBox

(double.Parse(strbox[0]), double.Parse(strbox[1]),

double.Parse(strbox[2]), double.Parse(strbox[3]));

//Call custom method that sets up the map with the requested tilesize

SharpMap.Map myMap = MapHelper.InitializeMap(new System.Drawing.Size(tilesize, tilesize));

//Center on requested tile and set the appropriate view width

myMap.Center = box.GetCentroid();

myMap.Zoom = box.Width;

//Render the map

System.Drawing.Bitmap b = (System.Drawing.Bitmap)myMap.GetMap();

//Create a PNG image which supports transparency

context.Response.Clear();

context.Response.Expires = 10000000;

context.Response.ContentType = "image/png";

System.IO.MemoryStream MS = new System.IO.MemoryStream();

//Set background to the transparent color which will be see-through in Google Earth

b.MakeTransparent(myMap.BackColor);

b.Save(MS, System.Drawing.Imaging.ImageFormat.Png);

byte[] buffer = MS.ToArray();

//Send image response

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

// tidy up

b.Dispose();

context.Response.End();

}

The last thing we need to do is add the network link to GE. The easiest way to do this is to do this from within GE. From the menu Select Add –> Network link. Type a name for your network link and set the location to the URL of the XML service. Under “View-Based Refresh” , set the “When” parameter to “After camera stops”, and click OK, and you should be set to go !

Unfortunately GE doesn't provide you with the same smooth image transitions that it use for its own tiles, so you will have to do with the rather crude way of showing big red squares until the tiles have been loaded. Furthermore the BBOX GE requests isn't always very accurate, especially if you are looking south at an angle you will notice the BBOX is very much off.

The small demo application you can download below shows a world map with each country’s population density shown on a colorscale from blue to red. Copy the files to a virtual directory (make sure it runs as its own web-application, at least the sub-folders are located at the root of the webapplication). Set the network-link to point to the URL of the default.aspx page.

GE also supports vectordata to be served as KML. It could be interesting to see who comes up with a "SharpMap KML Vector Server" first :-)

...or how to upload an ESRI Shapefile to PostGIS.

I've often been asked how to copy data from a shapefile to a PostGIS database. PostGIS comes with a commandline-tool for this (shp2pgsql.exe), but all it does is generate a huge SQL-textfile that you will need to run afterwards - Not very efficient I think - especially with the ASCII-representation of the geometry. Furthermore I've had several problems with it regarding many international letters in the attributes.

So why not try to let Npgsql and SharpMap do the job?

I've been working a bit with a small tool that makes it easy to upload an entire shapefile to a PostGreSQL/PostGIS database using SharpMap.

Below are some of the PostGIS/SharpMap related code explained:

First we create a Npgsql connection

NpgsqlCommand command = new NpgsqlCommand
();
command.Connection = conn;

The next step is to add a geometry column (see in the full source on how you create the table with all the attributes). In this case we set the spatial reference ID to '-1' and name the geometry column 'geom'.

command.ExecuteNonQuery();

Now we are ready to upload to the database, so lets get hold of that shapefile! First we set up a datasource:

SharpMap.Data.Providers.ShapeFile shp = new SharpMap.Data.Providers.ShapeFile(@"C:\data\MyShape.shp", false);

We can now query all the feature object IDs, by using an extents-query on the full extents:

conn.Open();
List<uint> indexes = shp.GetObjectIDsInView(shp.GetExtents());

...and then loop through all the features:

foreach (uint idx in indexes)
{
SharpMap.Data.FeatureDataRow
feature = shp.GetFeature(idx);

command.CommandText = "INSERT INTO \"myTable\" (\"geom\") VALUES (GeomFromWKB(:geom,:srid));"
;
.Bytea);
command.Parameters[":geom"
].Value = feature.Geometry.AsBinary(); //Add the geometry as Well-Known Binary
.Integer);
//Set the SRID of the geometry - this must match the SRID we used when the column was created
command.Parameters[":srid"].Value = -1;

//TODO: Add parameters for remaining columns if nessesary (in that case alter the INSERT commandtext accordingly)

command.ExecuteNonQuery();
}
//Clean up
conn.Close();
shp.Close();

...and that is all there is to it !

The great thing about this, is that it is easy to change this to take any other SharpMap datasource and upload as well. And with Christians OGR extension you can suddenly upload a bunch of datasource directly to PostGIS.

Download the full source and compiled binaries here: Shape2Pgsql.zip (624,3 KB) (updated April 26, 2006)

For some reason Microsoft made it pretty hard to work with anything but 24bit images. This is even though they provide you with several pixel formats, but no way of setting and getting the values of a pixel. If you use the SetPixel(x,y) or GetPixel(x,y) methods, your application will fail. There are plenty of articles and blogs on the Internet on how to do direct access on 1bit and 24bit, but I wasn't able to find anything on 8bit.

This article will cover some of the basics on how to access 8 bit greyscale or indexed images, by accessing the bitmapdata directly in memory. This also has the benefit of being much faster than the Set/GetPixel methods provided by the .NET Framework.

Before we can access the memory directly, we must lock its place in memory. We can do this by calling the Bitmap.LockBits() method:

`BitmapData bmd  = myBitmap.LockBits(new Rectangle(0, 0, myBitmap.Width, myBitmap.Height),                                    ImageLockMode.ReadWrite, myBitmap.PixelFormat);`

Likewise when we are done using the BitmapData, remember to unlock the data:

`myBitmap.UnlockBits(bmd);`

Now we need a method that can access the BitmapData. Lets make our own SetPixel and GetPixel method. Here we assume that we are dealing with 8bit pixels. We also add the 'unsafe' keyword since direct memory access isn't thread safe. I won't cover the Stride and Scan0 values. Bob Powell has a nice article on this.

```public unsafe void SetPixel(int x, int y, byte c)
{
byte* p = (byte *)bmd.Scan0.ToPointer();
int offset=y*bmd.Stride+(x);
p[offset] = c;
}

public unsafe Byte GetPixel(int x, int y)
{
byte* p = (byte *)bmd.Scan0.ToPointer();
int offset=y*bmd.Stride+x;
return p[offset];
}```

It is worth noting that GetPixel only returns a byte and not a color. The byte represents a number between 0 and 255. Each of the values is actually an index to a color palette. The palette could specify that for instance index 0 is black, index 1 is red, index 3 is blue etc. If you want a greyscale image, we can override the color palette. Let's set index 0 to black, index 255 to white, and linearly distribute the grayscale in between.

```public static void SetGrayscalePalette(Bitmap b)
{
ColorPalette pal = b.Palette;
for(int i = 0; i < 256; i++)
pal.Entries[i] = Color.FromArgb( 255, i, i, i );
b.Palette = pal;
}```

You can easily override this palette to specify other than grayscale images.

We can likewise create a function that can convert an index to a System.Drawing.Color. If you are working with a grayscale image, there is probably no need for this.

```public System.Drawing.Color GetColorFromIndex(byte c)
{
return = myBitmap.Palette.Entries[c];
}```

Now let's put it all together into an easy-to-use 8bit image access class. Remember to allow unsafe code blocks before compiling.

```using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace ImageProc
{
/// <summary>
/// </summary>
public class Image8Bit : IDisposable
{
private BitmapData bmd;
private Bitmap b;
/// <summary>
/// Locks an 8bit image in memory for fast get/set pixel functions.
/// Remember to Dispose object to release memory.
/// </summary>      /// Bitmap reference
public Image8Bit (Bitmap bitmap)
{
if(bitmap.PixelFormat!=System.Drawing.Imaging.PixelFormat.Format8bppIndexed)
throw(new System.Exception("Invalid PixelFormat. 8 bit indexed required"));
b = bitmap; //Store a private reference to the bitmap
bmd = b.LockBits(new Rectangle(0, 0, b.Width, b.Height),                          ImageLockMode.ReadWrite, b.PixelFormat);
}

/// <summary>
/// Releases memory
/// </summary>
public void Dispose()
{
b.UnlockBits(bmd);
}

/// <summary>
/// Gets color of an 8bit-pixel
/// </summary>
/// <param name="x">Row</param>
/// <param name="y">Column</param>
/// <returns>Color of pixel</returns>
public unsafe System.Drawing.Color GetPixel(int x, int y)
{
byte* p = (byte *)bmd.Scan0.ToPointer();
//always assumes 8 bit per pixels
int offset=y*bmd.Stride+x;
return GetColorFromIndex(p[offset]);
}

/// <summary>
/// Sets color of an 8bit-pixel
/// </summary>
/// <param name="x">Row</param>
/// <param name="y">Column</param>
/// <param name="c">Color index</param>
public unsafe void SetPixel(int x, int y, byte c)
{
byte* p = (byte *)bmd.Scan0.ToPointer();
//always assumes 8 bit per pixels
int offset=y*bmd.Stride+(x);
p[offset] = c;
}

/// <summary>
/// Sets the palette for the referenced image to Grayscale
/// </summary>
public void MakeGrayscale()
{
SetGrayscalePalette(this.b);
}

/// <summary>
/// Sets the palette of an image to grayscales (0=black, 255=white)
/// </summary>
/// <param name="b">Bitmap to set palette on</param>
public static void SetGrayscalePalette(Bitmap b)
{
ColorPalette pal = b.Palette;
for(int i = 0; i < 256; i++)
pal.Entries[i] = Color.FromArgb( 255, i, i, i );
b.Palette = pal;
}

private System.Drawing.Color GetColorFromIndex(byte c)
{
return = b.Palette.Entries[c];
}
}
}```
For a long time I wanted to start using a better blog-engine, and have now finally upgraded to dasBlog, a great ASP.NET-based blogging engine. At the same time I moved it to a new URL, so from now on, you can find my blog at www.sharpgis.net