The DEM Shaded Overlays

 

The default Bing Maps road style uses a “hillshade” effect to give an impression of underlying terrain. It’s a relatively subtle, but surprisingly powerful technique to enhance the appearance of map layers, as demonstrated by comparing the following two tiles:

image
Without hillshading
image
With hillshading

In this post, I’ll describe how to create your own hillshade overlay from digital elevation model (DEM) data, using the GDAL toolset.

By creating the overlay as a set of semi-transparent tiles, rather than pre-rendered into the tiles as shown above, you can place them on top of any Bing Maps/Google Maps et al. tilelayer to represent the underlying terrain.

The process I’ve followed is based on the work of others, most notably PerryGeo, and you can find some other guides on the internet to achieve this same effect. However, I found some of the existing guides on the subject to be either out-of-date or require knowledge of Linux BASH commands etc., so I hope that some of you will find this new step-by-step guide helpful.

1.) Acquire a DEM terrain model

To start with, you’re going to need some source data about the underlying terrain of the earth from which to calculate your hillshade. There’s lots of places to acquire this data from; Perhaps the easiest to use (assuming you’ve got Google Earth installed) is to open the kmz file available from http://www.ambiotek.com/topoview. This uses Google Earth as a graphical interface for v4.1 of the  elevation dataset gathered by the Shuttle Radar Topography Mission (SRTM), from which you can click to download individual DEM tiles covering 5°x 5°, as shown below:

Alternatively, you can access these files directly from the KCL server (my former university, incidentally) at http://srtm.geog.kcl.ac.uk/portal/srtm41/srtm_data_geotiff/

The data is provided in GeoTIFF format. You can load one of these tiles up in any graphics program that can load TIFF files, but it won’t look very interesting yet. The height information is encoded in additional metadata that will be ignored by normal graphics programs, so you’ll probably just get an image like this (this is srtm_36_02.tif):

Black parts show the presence of data in the underlying file, which we’ll subsequently process using GDAL tools to create shaded images.

2.) Reproject to Spherical Mercator

Most DEM data sources, including the SRTM data I linked to above, are provided in Plate Carree projection – i.e. WGS84 coordinates of longitude are mapped directly to the x axis of the image, while latitude is mapped directly to the y axis. Before we create tiles from this data suitable for overlay on Bing Maps, Google Maps, et al. we therefore need to transform it into the Spherical Mercator projection. You can do this using gdalwarp, as follows:

gdalwarp -dstnodata 0 -tr 305.7481 305.7481 -multi -co "TILED=YES" -t_srs EPSG:3857 srtm_36_02.tif srtm_36_02_warped.tif

The full list of parameters accepted by gdalwarp are listed here,  but the options I set are as follows:

  • dstnodata states what value to use to represent nodata values (the equivalent of null in a SQL database, for example). I’ve set a value of 0 (i.e. black).
  • tr gives the target resolution in x and y dimensions. The SRTM data I’m using was recorded at 90m resolution, so you might think that this should be set to 90 90. However, I’m going to be using this data for display on Bing Maps at different zoom levels, which will necessarily involve resampling the image.  Therefore, you should set this value to the resolution (in metres/pixel) of the maximum zoom level on which you plan to overlay your data. (Remember that maximum zoom level will have the smallest resolution). You can obtain this value from my Bing Maps Ready Reckoner. In the case above, I’m planning overlaying my data on Zoom Level 9 and above, so I set a value of 305.7481 (in both dimensions). If I’d wanted to go to Zoom Level 10, I would have decreased this to 152.87 instead.
  • multi allows parallel processing
  • co “TILED=YES” is a format-specific option that states that the output TIFF file should be tiled rather than stripped (see http://www.fileformat.info/format/tiff/egff.htm for an explanation of the difference)
  • t_srs gives the destination spatial reference system into which the image should be reprojected. In this case, EPSG:3857, as used by Bing Maps, Google Maps etc.

The resulting image, srtm_36_02_warped.tif, will still be a GeoTIFF file, but will now be projected as follows. The height and width of the output image will depend on the target resolution you specified in the tr parameter:

 

3.) Convert from DEM to Hillshade

The warped GeoTIFF file has height data encoded in it, but we want to translate that information into a visible shaded effect, and for this we can use gdaldem.

gdaldem actually provides several interesting functions related to working with DEM data, including the ability to derive contour lines, and create shaded relief maps. Maybe I’ll write about these another time, but for this example we want to use the hillshade mode. You can shade the warped image created in the previous step as follows:

gdaldem hillshade srtm_36_02_warped.tif srtm_36_02_warped_hillshade.tif -z 2 -co "TFW=YES"

This time, I’m only supplying two additional parameters:

  • z is a scaling factor applied to the generated hillside image that accentuates the hills, increasing the contrast of the image. I provided a value of 2 just to enhance the effect a bit, but you might decide you don’t need this.
  • co “TFW=YES” specifies that the output image should be created with an accompanying “world file”. This is a simple ASCII text file that provides additional information about the geographic extents of the created image, which we’ll need to use in a later step to line the hillshade image up with the Bing Maps tiling system. You can look up more information about world files on wikipedia.

There are additional parameters that allow you to specify the direction and the angle of the light source from which the simulated shadows will be created.

The result of executing the above code will be another TIFF file, in which the background is black, and the elevation data from the DEM has been converted into shades of grey, as follows:

 

At this stage, you could stop if you wanted to, and simply create a tile layer from the hillshaded image, which would look a bit like this:

 

Which makes the landscape of North Wales look a bit like the Moon, I think…

To make the data slightly more usable, we need to carry on with a few more tweaks.

4.) Making a Semi-Transparent Overlay

Currently, our hillshade image is opaque, with the shadows cast by terrain represented by variations in brightness of the colour used. To make this into an re-usable overlay that can be used on top of other layers, we need to make the image semitransparent, with shadows cast by terrain being represented by variations in opacity instead.

There are several ways of modifying the image data to achieve this effect. You could do it in Photoshop or another graphics program, for example, or using the graphics libraries in C# or PHP. Since I’m currently trying to learn Python, and GDAL is quite closely linked with Python, I’ll try to do it using the Python Imaging Library instead.

The following Python script makes a number of tweaks to the image above. Firstly, it converts it to a pure greyscale image (while the image above looks greyscale, it’s actually using a colour palette). It then inverts the image, turning it into a negative image. The reason for the inversion is that we then copy the (single) channel of the greyscale image into the opacity channel of a new RGBA image – areas that were very light in the source want to have very low opacity in the transparent image, and vice-versa, so the channel needs to be inverted.

Finally, we scan through the data to find instances of pixels that are pure black (RGBA value 0, 0, 0, 255) –this was the nodata value we set in step one – and replace them with pure transparent pixels (0, 0, 0, 0). The alpha channel in the tuples of any other pixels is also lightened slightly – I chose a value of 74 somewhat arbitrarily because I thought the resulting image looked good – you can choose whatever value you want, or none at all.
[php]
from PIL import Image as PImage
from PIL import ImageOps

# Load the source file
src = PImage.open("srtm_36_02_warped_hillshade.tif")

# Convert to single channel
grey = ImageOps.grayscale(src)

# Make negative image
neg = ImageOps.invert(grey)

# Split channels
bands = neg.split()

# Create a new (black) image
black = PImage.new(‘RGBA’, src.size)

# Copy inverted source into alpha channel of black image
black.putalpha(bands[0])

# Return a pixel access object that can be used to read and modify pixels
pixdata = black.load()

# Loop through image data
for y in xrange(black.size[1]):
for x in xrange(black.size[0]):
# Replace black pixels with pure transparent
if pixdata[x, y] == (0, 0, 0, 255):
pixdata[x, y] = (0, 0, 0, 0)
# Lighten pixels slightly
else:
a = pixdata[x, y]
pixdata[x, y] = a[:-1] + (a[-1]-74,)

# Save as PNG
black.save("srtm_36_02_warped_hillshade_alpha.png", "png")
[/php]
(Much of the logic in this script came from here). The resulting image will be a PNG file, in which darker shadows are represented by increasingly opaque black parts, while lighter shadows are more transparent:

 

Vaadin 6.6 Ships with GWT 2.3

Accompanying the GWT 2.3 release, Vaadin is happy to announce version 6.6 of the Vaadin Framework. Vaadin is a server-side UI component framework that uses GWT on the client-side for rich user experience. With origins in Finland (a “vaadin” is a reindeer), there is now a very active Vaadin community world-wide. The framework has become especially popular during the last two years, with nearly twenty thousand downloads monthly.

Vaadin UI components are similar to GWT widgets, but their state is stored at the server. Every component has a client-side peer widget responsible for the presentation, and the synchronization between the server and the browser is automatically handled by the framework.

This makes development with Vaadin fast. It is mainly used to develop business web applications where pure client-side web application development is not a feasible option, but the web browser as a platform provides unparalleled benefits. One can think of Vaadin as a simplified Swing for web applications.

Touch support and Eclipse plug-in

Vaadin 6.6 follows the latest trends in web application development and adds touch device support. With GWT’s new touch features, we were able to touch-enable all Vaadin components. Touch scrolling, selections, and drag and drop work out-of-the-box. Also thanks to GWT, we were able to add official support for Internet Explorer 9, which has been requested a few times already.

In addition to the new framework version there is a new version of the Vaadin plug-in for Eclipse available. The main addition is the visual editor for Vaadin that has now been included by default. With that you can visually design the user interface and then just continue editing the generated Java code to add some logic.

Summary

Over the years, we have seen the development team behind GWT doing an excellent job adding new functionality while keeping the framework as a solid platform for our development.

Today we are also actively contributing new widgets to the GWT community. You can find some of them hosted at Google Code and also available in the Vaadin Add-on Directory. Take a look at the GWT Graphics, SparkLines and SimpleGesture for some interesting examples.

Vaadin 6.6 is a big thing for us and to celebrate it, we decided to release it at Google I/O 2011. Find out more and download at vaadin.com.

Creating a User-Contributed Map: Look, Ma – No server side scripts!

Posted by Keir Clarke, Virtual Tourism Blog Author and Google Maps Mania Blog Contributor

Pamela Fox wrote a wonderful tutorial in November called Creating a User-Contributed Map with PHP and Google Spreadsheets. However if you are like me, the thought of having to tackle server-side scripting sends you running for the hills. Fortunately, the recent release of forms for Google Spreadsheets means it is now possible (with just a tiny bit of hacking and wizardry) to create a user contributed map without any server-side scripting and with the added bonus of Google hosting the data for you.

  1. The first step is to create a form for Google Spreadsheets at this page.

    The information that we need in order to add a contributor to our map is their name, latitude, and longitude. Of course, if you want more information on your map, you can always add more fields to the form later.

    • The first question we will ask is ‘What is your name?’. Type this into the ‘Question Title’ box. The default question type is ‘text’ – leave this as it is. After you have completed the ‘Question Title’ press ‘save’.
    • Now add the second question by clicking ‘+ Add a question’ and this time type ‘Latitude’ in the Question Title box. Again leave the question type as ‘text’ and press ‘save’ again.
    • Add one more question with ‘Longitude’ as the ‘Question Title’.
  2. The second step (and the only one that requires some coding) is to hack the generated spreadsheet form so that instead of having to type in a latitude and longitude manually, our users can just click on a map to show where they live. To do this, we create a map and then assign an event listener for the map 'click' event that writes the values of the clicked coordinate into the form input fields. The code that accomplishes that is shown below:

    var map = new GMap2(document.getElementById("map_canvas"));
    map.setCenter(new GLatLng(37.4419, -122.1419), 13);
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    
    GEvent.addListener(map, 'click', function(overlay, latlng) {
      var LatLngStr = "Lat = " + latlng.lat() + ", Long = " + latlng.lng();
      map.openInfoWindow(latlng, LatLngStr);
      document.getElementById("latbox").value = latlng.lat();
      document.getElementById("lonbox").value = latlng.lng();
    });
    

    The full HTML for the form and map is here. This page extracts the latitude and longitude when a user clicks on the map and automatically fills in the input boxes for latitude and longitude in the spreadsheet form, and also lets the user fill in their name. The important things to remember about modifying the generated spreadsheet form is that the form field names remain the same (e.g. the name for the latitude input is ‘single:2’), and that the form action remains the same (e.g. ‘http://spreadsheets.google.com/formResponse?key=pHxwMuyQhRdSwN9QcKaqWVA’).

    Now that you understand how the simple map-based form works, feel free to hack it further. Here’s an example using the same form that integrates the GClientGeocoder to let users type in an address and then stores the resulting coordinate in hidden input fields.

  3. Once you’ve successfully modified the form, all you need to do is use the Spreadsheet Map wizard to create your user-contributed map.

    The wizard will do all the work of creating your map and generating the code, and give you something like the map embedded below. You could also try out generating KML from the spreadsheet with the techniques from the Spreadsheets Mapper tool.

    Check out the example output of the spreadsheets map wizard.