This blog is going to look at the mathematical calculations involved in rendering 2D GIS vector data, based on a particular area that we want to see on a map. I.e. converting vertices from map space into view space, and back.

For each vertex in a feature geometry, we need to perform a set of operations to calculate the screen position, based on our chosen location, scale, and rotation. Also, most applications will use top left as the origin rather than bottom left for map projections.

Normally, we would use client software such as OpenLayers, or application software such as GeoServer to make these calculations (and render the points, lines, or polygons) for us, however, occasionally it is more convenient to make the calculations required ourselves. E.g. generation of an image file on a server when the data is not available as a WMS through GeoServer.

At thinkWhere, we have implemented these calculations in a number of programming languages over the years as the languages we have used have changed. We have gone from C++, through C# and Actionscript (Flash), to Python and Javascript.

The Maths

To make the calculations we use Affine Transformations. For 2D data, these take the form of 3×3 Matrices which can be applied to a point location, producing a modified point.

We can create a number of transformations, each of which represents an action on the data. E.g translate, scale, or rotate the point.

These can be combined through matrix multiplication into a single transformation.

We can also calculate the inverse of a matrix, making it just as easy to perform the reverse set of actions.

The beauty of this approach is that we can apply a number of actions to each vertex in a small number of arithmetic operations making them quick to apply. Even for rotation, the sin/cosine values are calculated once, and the calculated matrix values used in simple multiplications and additions from then on. Once the completed matrix has been generated, the calculations required for each vertex are:

x' = (a * x) + (b * y) + c
y' = (d * x) + (e * y) + f

The Good News

The good news is that once we have created a class to perform the matrix arithmetic, we don’t have to think about it again. We can then create a sequence of actions which will transform our map coordinates to view coordinates.

Translate the data based on our chosen centre point – centring the data at 0,0

Scale the data based on our chosen view scale

Rotate the data around the centre if required

Flip the horizontal axis to switch the origin from bottom left to top left

Translate again to the centre of our view (based on the view size)

The example below shows this in action.

Application

This sample application has been written using an HTML5 Canvas to draw a GIS dataset from a GeoJSON file. It uses the turf library to assist in reading the GeoJSON files.

It uses an implementation of affine transformations to calculate the necessary transform to convert map coordinates in the GeoJSON file to screen coordinates. A standard class called CanvasRenderingContext2D draws the features. We have added additional members to make the drawing easier. This object already implements affine transformations. You can apply individual actions using the rotate(), scale(), and translate() methods, which alter the current transformation to allow you to build up a set of actions, or you can supply the six relevant parameters of the matrix in a single call to transform().

We have used the approach of calculating the matrix ourselves, in order to also produce the inverse transformation. This is then used to make the reverse calculation I.e. for a point clicked on the map, find the map coordinate that this relates to in order to then search for the clicked feature within the source data.

The code below uses the view control values to create the required transformation, and pass this to the CanvasRenderingContext2D

When a data file is loaded, the maximum extent of the features is calculated, and the controls are set up accordingly. When the controls are modified the transformation is adjusted, and the features redrawn.

Loops and more

Since it it quite simple to set up a set of actions passing in the various parameters, we can make use of loops to run though a variety of settings and start having some fun.

Filed under: Development, Mapping, python]]>https://blog.thinkwhere.com/2017/10/02/demystifying-coordinate-transformations/feed/0alastaircarsonAddress Search OS OpenNames with PostGIS, SQLAlchemy and Python – PART 2https://blog.thinkwhere.com/2017/08/04/address-search-os-opennames-with-postgis-sqlalchemy-and-python-part-2/
https://blog.thinkwhere.com/2017/08/04/address-search-os-opennames-with-postgis-sqlalchemy-and-python-part-2/#respondFri, 04 Aug 2017 10:16:39 +0000http://blog.thinkwhere.com/?p=1255Continue reading "Address Search OS OpenNames with PostGIS, SQLAlchemy and Python – PART 2"]]>Part 1 of this post outlined how to configure a PostGIS database to allow us to run Full Text searches against the OS OpenNames dataset.

In Part 2 we look at writing a simple Python 3 CLI app that will show you how easy it is to integrate this powerful functionality into your apps and APIs. Other than Python the only dependency we need is the SQLAlchemy ORM to let our app communicate with Postgres.

Installing SQLAlchemy

SQLAlchemy can be installed using pip. It is dependent on psycopg2, which you may struggle to install on Mac without Postgres present, which is frustrating (however solutions can be found on Stack Overflow).

A simple address search CLI

Let me draw your attention to…

Hopefully this script is fairly easy to follow, but there are a couple of lines to draw your attention to

Line 4 – Note we have to tell SQLAlchemy we’re using the Postgres dialect so it understands TSVECTOR.

Lines 8 – 12 is simply SQLAlchemy boiler plate that sets up our connection and session for the app. You’ll need to swap out the connection details for your own.

Line 25 – is very important, here we append the OR operator to every word the user has supplied, meaning we’re returning addresses. You could extend this to allow the user to specify on exact match operator and change this to an & search.

Line 26 – Finally note we ask SQLAlchemy to match our search, and importantly we must supply the postgresql_reconfig param to say we’re searching in English. This is vital or you wont get the matches you expect.

Running our app

We can run our app from the command line simply by entering the following command:

python address_search.py 'forth street'

And we see our app print out all matching addresses that contain either Forth or Street

Ends

Hopefully you can see how easy it would be take the above code and integrate it into your apps and APIs. I hope you’ve found these tutorials useful. Happy text searching!

Filed under: Development, Uncategorized]]>https://blog.thinkwhere.com/2017/08/04/address-search-os-opennames-with-postgis-sqlalchemy-and-python-part-2/feed/0Iainaddress-searchAddress Search OS OpenNames with PostGIS, SQLAlchemy and Python – PART 1https://blog.thinkwhere.com/2017/07/10/address-search-os-opennames-with-postgis-sqlalchemy-and-python-part-1/
https://blog.thinkwhere.com/2017/07/10/address-search-os-opennames-with-postgis-sqlalchemy-and-python-part-1/#respondMon, 10 Jul 2017 11:34:05 +0000http://blog.thinkwhere.com/?p=1246Continue reading "Address Search OS OpenNames with PostGIS, SQLAlchemy and Python – PART 1"]]>In this two part post we’ll look at implementing an address search using the Ordnance Survey Open Names dataset. We’ll use the power of Postgres with the PostGIS extension leveraging it’s built in Full Text Search, and use Python and the SQLAlchemy ORM to create a simple CLI.

Part 1 – Data Load and DB Config

Address Data

The UK is badly served for free address data. The best we have is the Ordnance Survey OpenNames dataset. It will work as a Postcode lookup or a street finder (at a push), but the dataset would require a lot of additional processing to be a useful address search. OS really want you to purchase AddressBase.

That said, OpenNames will suffice for this example and it should be easy to extend the example to a fuller dataset if you’re lucky enough to have one.

Loading Data to PostGIS

You can download OpenNames as either CSV, or GML. I’d recommend GML as it’s simpler to load it into PostGIS using OGR2OGR.

Once you unzip the archive you’ll see that the files are referenced according to the British National Grid, so you can load as much or as little as you want.

We’ll load NS68 which contains addresses in my home town of Stirling, as follows (swap out the values for your db):

If you look at the data in your new column you’ll see that it now contains text tokens representing the address data.

Increase accuracy by concatenating multiple columns

Note that we’re concatenating 2 columns together in this update statement – text and localid. In our case the reason for doing this is that the postcode in the localid column is stored without a space, meaning our search will return a result if the user enters a postcode without a space.

However, it should be clear if we had better address data, we could concat multiple columns. Meaning if a user searched for “1 Main St, Stirling, FK3 4GG” we would be able to return an accurate match.

Add an Index for faster searching

Now that we have data set up we can add an index to our new column which will ensure searches are fast:

CREATE INDEX textsearch_idx ON open_names USING GIN (textsearchable);

Let’s do some searches

Now lets query our new column to see if we can find some matches using the TO_TSQUERY function

Here we find we have 41 streets in Stirling area containing the word avenue. You’ll note that I don’t need to worry about lowercase, uppercase or where the word might appear in the string. Full text search takes care of that for me

The @@ operator basically means that the query matches the tsvector column.

Using AND and OR for better matches

A very powerful feature of Postgres’ Full Text Search is the ability to find matches contain all or some of the words in the query using the AND & operator or the OR | operator, as these examples show:

Again it should be easy to see how powerful text searches could be built for complex text documents.

A final note on Triggers

While our address data is fairly static, if you had a table where users were regularly editing address data, or any other columns you wanted to run a full text search on, you should consider adding a trigger to keep the TSVECTOR column up to date, as outlined here.

Up Next

Hopefully Part 1 has demonstrated how it is very easy to set up powerful text searching in Postgres. In Part 2 we’ll look at how we can use Python and SQLAlchemy to allow you to integrate this functionality into your apps and APIs.

Filed under: Development, PostGIS, python, Tutorials]]>https://blog.thinkwhere.com/2017/07/10/address-search-os-opennames-with-postgis-sqlalchemy-and-python-part-1/feed/0Iainaddress-searchRestoring a Postgres database to AWS RDS using Dockerhttps://blog.thinkwhere.com/2017/05/24/restoring-a-postgres-database-to-aws-rds-using-docker/
https://blog.thinkwhere.com/2017/05/24/restoring-a-postgres-database-to-aws-rds-using-docker/#respondWed, 24 May 2017 08:30:04 +0000http://blog.thinkwhere.com/?p=1238Continue reading "Restoring a Postgres database to AWS RDS using Docker"]]>In this post I look at using Docker to restore a Postgres dump file to a Postgres database running in the cloud on AWS RDS.

Keep it clean

One of the big selling points of docker, for me, is that I can have lots of apps and utils running in nice containers on my dev laptop, without having to install them locally. This ensures my laptop stays nice and responsive and I don’t clutter/break my laptop with lots of weird dependencies and running processes that I’m then too scared to delete.

Postgres is a good example – I don’t want to install it locally, but I do need access to the command line tools like psql and pg_restore, to be able to work with my databases effectively.

One way of accessing these tools would be to ssh onto the AWS cloud instances, but there’s a bunch of reasons most pertinently security (not to mention the faff) why you’d want to avoid that every time you want to run some sql. So let’s look at how we use Docker to ease the pain instead.

Start Me Up

With Docker installed you can build this simple Dockerfile to create a local Postgres container. The User and Password env vars aren’t strictly required, however, if you want to actually connect to the containerised DB, it’s pretty handy

You can build, run and connect to the container as follows (assumes you are on Mac)

Note line 4 where I map the data-load dir I created at line 1 to a new directory called data-loader inside my container. This means that when I copy the Postgres dump file into my local data-load directory, it will be available to the postgres tools available in the container.

Line 6 allows me to connect to the container, swap the imageId for your locally running containerID.

Restoring your database with pg_restore

I’ll assume you already have a Postgres database set up within the AWS cloud. So now we have connected to our container, we can use pg_restore to use restore our dumpfile into AWS (note this command will prompt you for the admin password)

A note on schemas

If you’re doing a partial restore, you may want to restore your dumpfile to a separate schema. Unfortunately there appears to be no way to do this from the command line. What you have to do is to rename the public schema, create a new public schema and restore into that, then reverse the process.

I have had a great week placement at thinkWhere. During my week placement I was presented with a variety of opportunities. I had a great chance to meet everyone from the various parts of the business including CEO, Portfolio Manager, Business Managers, Accounts Managers, Developers, Service Desk Consultants and Office Administrators.

I have learned how the agile development systems work such as Scrum, as well as the differences between Agile and Waterfall. I have taken part in the different ceremonies including daily stand up, backlog refinement, demo and sprint planning.

Attending the Scrum daily-stand up

I have also learned about GIS (Geographical Information Systems) and the theMapCloud. I have also created my own map using QGIS where I am from in Côte d’Ivoire (Ivory Coast).

My first QGIS map of Côte d’Ivoire

The thinkWhere development team also worked with me to develop my coding skills including help with JavaScript, HTML and CSS using PyCharm. I used these skills to script a page showing a graph of theMapCloud usage metrics.

The role has allowed me to learn key skills and competencies of IT and business systems. On top of this I delivered 30 minutes of presentation about myself and a project I am working on at university.

One of the best things about the company is the people. They were very friendly, approachable and well organised. I have also made a great network of colleagues and made new friends.

I have really enjoyed my work placement. I have learnt a lot and have gained skills that I will take forward with me. I have also been given many opportunities and many new experiences. I’ve gained a deeper understanding of how large IT projects work, which is going to help me in the future.

Developing my JavaScript, HTML & CSS skills using PyCharm.

Being part of this placement has also helped me to develop my interview skills and my job prospects. It is also very valuable experience for my CV.

I hope to be back at thinkWhere again one day!

Filed under: Uncategorized]]>https://blog.thinkwhere.com/2017/04/07/my-work-placement-week-thinkwhere/feed/2yacthinkwhereHOT Tasking Manager 3.0 Development Underway at thinkWherehttps://blog.thinkwhere.com/2017/03/15/hot-tasking-manager-3-0-development-underway-at-thinkwhere/
https://blog.thinkwhere.com/2017/03/15/hot-tasking-manager-3-0-development-underway-at-thinkwhere/#respondWed, 15 Mar 2017 15:58:37 +0000http://blog.thinkwhere.com/?p=1191Continue reading "HOT Tasking Manager 3.0 Development Underway at thinkWhere"]]>We get to work on some great projects here at thinkWhere, but we’re particularly proud of the project we’ve just started with the Humanitarian OpenStreetMap Team (HOT) to develop the Tasking Manager version 3.0 (TM3). It’s great to work in an industry where the work we do with maps can have such a tangible impact on the humanitarian effort. thinkWhere support this wherever we can by supporting MapAction by both supporting my own personal volunteering (which you can read more about here) and through fundraising efforts such the running the Stirling Marathon, which is open for sponsorship here so please donate if you can! Therefore being given the opportunity to also get involved with the HOT Community and deliver TM3 is something we’re extremely proud of.

The current HOT Tasking Manager (TM2) coordinates volunteer mapper contribution to OpenStreetMap, meaning the global network of HOT volunteers can map affected areas efficiently providing disaster responders on the ground such as MapAction, MSF and the Red Cross access to detailed mapping during the response.

Following a significant increase in the capture of OSM data through initiatives such as Missing Maps, and subsequent loads on existing servers and software, the development of TM3 aims to better meet the needs of mappers, validators and project managers. This will be achieved by taking advantage of the very latest advances and innovations in web development frameworks and methodologies.

“We are very excited to be working with thinkWhere to develop the next generation of HOT’s Tasking Manager application. The team at thinkWhere brings a wealth of geospatial development experience, talent and insight to the project. Used by thousands of people around the world, our Tasking Manager software is the key technology component that enables our humanitarian mapping work and having thinkWhere as partners ensures the development project will be a success and deliver a great result for our community”.

In early February 2017, we travelled to HOT’s office in Washington DC for the project initiation meeting with various project stakeholders to discuss initial requirements and wireframe designs.

This engagement with some of the largest users of the Tasking Manager to discuss functionality and solicit feedback on how features might be implemented was a great way to start the project. A long, but very productive day, the discussion involved representatives from Missing Maps, YouthMappers, TeachOSM, GeoCenter, the US State Department’s Humanitarian Information Unit, Mapbox, HOT Project Managers, American Red Cross and Ethan Nelson, the lead community development volunteer.

thinkWhere’s Chief Executive Alan Moore said…

“We’re really delighted and privileged to be working with the team at HOT. Redevelopment of the Tasking Manager will be key to the future growth and sustainability of the humanitarian mapping effort across the world. The development work flows naturally from the innovative work we’ve been doing recently on theMapCloud, our new spatial data platform, and we’re keen to bring those advantages to the benefit of HOT and the global mapping community”.

Everyone is invited to participate in the process. Comments, questions and issues are needed and encouraged on the GitHub repository’s Issues tab, so please get involved!

Filed under: AngularJS, Development, Humanitarian, Mapping, OpenLayers]]>https://blog.thinkwhere.com/2017/03/15/hot-tasking-manager-3-0-development-underway-at-thinkwhere/feed/0davidcfranklandCounting Points and the Process Modeller in QGIShttps://blog.thinkwhere.com/2017/02/21/counting-points-and-the-process-modeller-in-qgis/
https://blog.thinkwhere.com/2017/02/21/counting-points-and-the-process-modeller-in-qgis/#respondTue, 21 Feb 2017 23:26:57 +0000http://blog.thinkwhere.com/?p=1162Continue reading "Counting Points and the Process Modeller in QGIS"]]>Here at thinkWhere we’ve recently been working with the automation tools in QGIS. The processing toolbox is a much underrated feature in QGIS, lacking the jazzy graphics of the ArcGIS equivalent it is, however, just as useful and functional from the point of view of doing multi-stage GIS analysis.

We recently had occasion to create a tool for a client that counted the number of features within a polygon and provide statistics for subsets of the features. Let’s try this again, for the sake of demonstration and talk about trees.

Here we have a series of suburbs arranged as polygons and trees as points. As you can see there are 5 types of tree in the dataset. A Spatialite or PostGIS database would make quick work of this, but you can also use the QGIS processing toolbox to iterate through this and count each aspect of the data.

Effectively from the point dataset we need to extract each of the attributes.

Extract by Attribute from Trees “Type = Beech” etc.

This creates effectively a subset of the input points dataset which can then be counted via the polygons.

We can then use the count points in polygon to count the number of points that sit inside each of the neighbourhoods.

Count Points in Polygon From Beech Subset of Input Points by Input Polygon, Create field “Beech”

Using standard QGIS this will create a new dataset each time you run an algorithm, but the great strength of the processing modeller is that these intermediate steps can run in the background as temporary layers, rather than confusing your users with multiple layers.

Of course what needs to happen now is that the next iteration (Birch) will need to be counted using the polygon dataset you created for the counts in the Beech dataset. If you think about it, the geography of that dataset is the same as the Input Polygon (the neighbourhoods). It also carries forward all the attributes for the layer as well. So for each iteration you are not using the original input polygons, but adding the new attribute information on for each count.

In the processing toolbox this looks like this:

When you run the model, you get a polygon shapefile with a new set of attributes showing the number of each of the tree types in the area. You can then generate graphs or use the data for other purposes.

This is only one of the many ways that the automation tools in QGIS can help you. It is also a really useful system for analysis. QGIS is hugely flexible and has a load of options for this. To learn more and see details of our QGIS training offerings please see our training page.

BrowserStack is a cloud-based platform for testing applications in various Operating Systems and browsers. It is used for both Continuous Integration (CI) and cross-browser testing. Selenium WebDriver is a tool for driving browsers to replicate and automate user journeys and assert presence and functionality of page elements.

We aim to integrate automated testing into our Continuous Integration pipeline, however a number of our more established products are not yet part of this pipeline. One such product is Location Centre which is used by many local authorities where the end-user often has limited control over the choice of OS and browser. This often restricts the development to suit the majority of browsers used and their degree of modernity. Despite not being part of our CI pipeline testing our software to ensure high quality is just as important. Therefore I’ll now provide an example of how simple and straightforward it is to automate tests for Location Centre using BrowserStack.

BrowserStack offers a 100 minute trial so I recommend you also try it out! The site provides a range of multi-system environments for manual and automated testing as shown in the image below.

BrowserStack runs the tests using Selenium WebDriver and these code examples serve as a great starting point. The tests can be scripted manually or by using Selenium IDE plugin for Firefox – the extension allows you to record the user steps with minimum coding, thus minimising hand-written code and saving you time. It provides hundreds of commands for element assertion, mouse position and many more. The tool decides by itself how to locate the element. The plugin is user-friendly and well-supported and the process of recording is quick and intuitive.

I have recorded the simple process of logging in to Location Centre, selecting the ‘Mapping’ tab and then zooming and panning the map.

Once created test cases can be exported in your language of choice – in our case it’s Python.

(File> Export Test As> Python 2 / unittest / WebDriver)

We can add the exported test case to our IDE. All we need to do now is modify the setup function to add the BrowserStack keypass and specify the browser and OS requirements.

We find it’s always worth starting the tests with the high risk browsers which is traditionally Internet Explorer which is used by the majority of Location Centre customers. Gov.UK recommends testing from IE8 and up, so we will run the test in IE8.

IE8 runs on Windows 7 and Windows XP, making it difficult to test locally. You could get IE8 from Microsoft virtual machine but BrowserStack makes it much easier. Using the BrowserStack tool we can get the capabilities and add them to the setUp function:

System capabilities and the authorisation information can be input into the setup:

You can now run the automated test with BrowserStack as shown in the GIF below.

The test can be played back and each step can be reviewed in turn. BrowserStack will provide you with a screenshot for any failed step (I have broken the one below on purpose!).

This service offers many useful features including localhost testing, ability to upload files and many more. There is no or very little coding required – although you may want to change an elements location or add some custom assertions, cursor movements or text inputs etc. Furthermore, there are no (or not as many) compatibility issues between the Selenium methods and the webdrivers which one experiences when testing locally.

You can utilise the vast Selenium library for replicating user journeys in the required system at the desired speed. BrowserStack also has integrated Cucumber and Behave used in Behaviour Driven Development (BDD) and testing. However, at the time of the writing this post, there were issues running those on Windows platforms. Overall, it is a great framework for compatibility testing.

Alongside the automation, exploratory tests still need to be in place to avoid kaleidoscopic bugs like this one found in our product mapTrunk…good job we caught this before Go-Live!

Aside from the work I do here at thinkWhere I also volunteer for the humanitarian mapping charity, MapAction. This year MapAction are fortunate to be part of the BBC Radio 4 appeal and have our message presented by Alexander Armstrong (Presenter of Pointless, amongst other things) which will air on Christmas Day at 7:54am and 6.56pm and on 29th December at 3:27pm. As part of the drive to raise awareness of MapAction, thinkWhere has posed some questions to me to find out more about what it’s like being a MapAction volunteer…

Can you tell us a bit about what MapAction does and how it helps during humanitarian crises?

MapAction is a humanitarian mapping charity that works through skilled volunteers. Its aim is to save lives and minimise suffering by making the response to humanitarian emergencies as efficient and effective as possible through the use of maps and spatial data.

When a disaster strikes, people’s lives can be destroyed within a matter of seconds. In a landscape transformed by the disaster, the challenge for responders is to know where to start.

MapAction deploys skilled volunteers to the scene of a disaster within hours of an alert. In the acute phase of a response, our mapped analysis helps coordinate search-and-rescue efforts and the delivery of emergency aid. As the situation on the ground evolves, it helps responders understand the changing needs of survivors.

As a long-term measure we also help to prepare government authorities, responders and communities in vulnerable countries for the impact of disasters before they strike.

Consequently over the last 11 years I’d heard lots about what it meant to be a MapAction volunteer, how much difference MapAction is able to make during an emergency and how rewarding being a volunteer was. MapAction as an organisation is also very well-known and respected within the wider GIS community.

Given I chose to follow a similar GIS career as my sister I was therefore also driven to become a volunteer, so eventually applied during a recruitment drive and was very pleased to be successful and able to join MapAction myself in 2014.

The MapAction team at a recent disaster simulation exercise

What kind of training do you get to prepare you for any missions you might get sent on?

MapAction volunteers are expected to participate in at least seven training weekends a year, keeping us up to date with the latest developments in the humanitarian and technical community.

Every year MapAction also runs an intensive simulation exercise, focusing on developing the skills we need to deliver our mapping service in the potentially challenging context of an emergency response.

Our training helps us make judgement calls about what sort of map products we should create given the time available and the volume of rapid requests coming in.

Recognising that the world is dealing with more conflict-related emergencies, MapAction has also boosted its security training so we can deploy safely to environments where the situation can be highly unpredictable.

Training involves simulations that enable us to ‘learn by doing’ in a practical and safe environment. This has included practising first aid, emergency communication procedures and negotiating with combatants. We hope none of this will ever be needed, but MapAction make a point of always preparing the team for all eventualities.

How do you balance your time between volunteering and working at thinkWhere?

MapAction is a big commitment. Aside from deploying to the field for emergencies we also provide remote support to emergencies when required, as well as actively training together as a team throughout the year, so the time commitment is significant.

Luckily I have a very understanding girlfriend (thanks Maddie!) and a very flexible employer in thinkWhere. thinkWhere are great at accommodating my MapAction training and volunteering around my work commitments, such as recently allowing me the time to deploy to Northern Iraq. Without this flexibility my volunteering with MapAction wouldn’t be possible.

Team thinkWhere raising money for MapAction by completing Total Warrior in 2015

Where in the world does your volunteering take you?

MapAction deploy to emergencies all around the world, a list of which can be found on the website here: maps.mapaction.org. MapAction doesn’t currently have any teams engaged in active responses, however since September we’ve responded to a number of high profile emergencies including the conflict related crisis in Nigeria affecting as many as 14 million people and Hurricane Matthew in Haiti, Jamaica and the Bahamas.

In November I also went on my first deployment with a fellow volunteer Naomi to Northern Iraq to map aid needs and distribution as a result of the conflict related crisis affecting the region.

QGIS training in Erbil, Iraq

What (from your own personal experience) is the most rewarding thing about volunteering for MapAction?

The most rewarding thing is being able to directly apply the skills I have from my work life into a completely different context i.e. the humanitarian world, in order to make a difference and help those in need. Meeting and working with the rest of the MapAction team who also share the same drive and commitment is also very rewarding.

Have you ever met the Royal Patron of MapAction, Prince Harry?

I haven’t personally met Prince Harry, although he did recently attend ‘Triplex’ in Norway which is a major international humanitarian field exercise organised by the International Humanitarian Partnership (IHP), where MapAction volunteers were participating. Prince Harry has an active interest and great knowledge of our work having been MapAction’s Royal Patron for the last 10 years since 2007. Maybe I’ll meet him one day!

How can others get involved with MapAction?

MapAction will be recruiting a new intake of volunteers in the New Year, so anyone with the right technical skills and an interest in joining our close-knit team should keep an eye on MapAction’s website and social media channels for more information about the skills and commitment required.

It’s certainly not for everyone and requires a flexible employer, like thinkWhere, to be willing to release you at short notice. But the benefits you gain in terms of honing your professional skills, making a difference and meeting like-minded people make it incredibly rewarding.

How can people help MapAction without becoming a volunteer?

The single easiest thing people can do is donate. MapAction doesn’t receive funding from large public appeals, so we rely on the generosity of our supporters. Your donation means we can continue to be responsive, agile and ready for action at any time.

MapAction’s approach has a powerful multiplier effect. Every pound you donate will influence the allocation of many thousands, if not millions, of pounds of humanitarian aid. And that means many more lives potentially saved.

MapAction is often referred to as the “best-kept secret” of the humanitarian world. The video featuring Prince Harry on the MapAction website aims to raise MapAction’s profile, so more people will get behind this unique organisation and help get more aid to more people.

How can we find out more?

Visit mapaction.org and watch the Prince Harry video which brings to life the pivotal role that MapAction plays in coordinating humanitarian aid.

The MapAction BBC Radio 4 appeal being presented by TV personality Alexander Armstrong goes out on Christmas Day at 7:54am and 6.56pm.

We’ve recently released a new product called mapTrunk. The app is built using the open source libraries AngularJS and OpenLayers 3 (among many others!). As part of our development efforts we looked into creating reusable modules. This blog post offers a high level introduction to AngularJS and OpenLayers 3 and shows how they can work together to create a reusable map scale bar module example.

AngularJS and OpenLayers 3

AngularJS is an open source JavaScript framework for creating web apps. It provides tools for making apps modular. AngularJS handles binding data which means the view (HTML) automatically updates when the model (JavaScript) updates. Other benefits of AngularJS include form validation in the browser, the ease of wiring an app up to a backend and the testability of the code. AngularJS also lets you extend the syntax of HTML and inject components into your HTML. This feature comes in handy when creating the scale bar module.

OpenLayers 3 is an open source mapping library. It provides tools for adding dynamic maps to an app. Commonly used mapping controls provided by OpenLayers include zooming in/out control, a mouse position control and a scale bar control.

The following example shows how to create a basic map with OpenLayers and AngularJS. The result is a map and a button to recenter the map. It also shows the user how many times they have centred the map.

HTML

Firstly we need to include the AngularJS and OpenLayers 3 libraries, add a div for the map and add a button. We also need to include the Angular app called “app”, which is created in JavaScript.

Creating the scale bar module

The OpenLayers library already has a scale bar module called ‘scale line’ built-in. An example can be found here. One of the requirements for mapTrunk was to create a scale line that can display distances in two units at the same time, metric and imperial.

To create a reusable module we can create a custom Angular directive. Angular directives basically let us create our own HTML syntax and inject components by using that HTML syntax. It makes the HTML code easier to read and hides the complexity of the component. In this blog we’re not going to go into the details of Angular directives so please see AngularJS’s documentation on directives for a full explanation.

First we need to create the Angular directive and decide what the HTML syntax is going to be. In the code snippet below we called the directive scaleLineControl. This translates into the HTML tag . The directive needs to have access to an OpenLayers map object to be able to add a scale line control to the map. The map object can be passed into the directive by adding it as a property to the HTML ‘map=”main.map”‘. The OpenLayers scale line control needs a HTML target ID so this ID can be given to the HTML directive as well. The scale line control is added to the OpenLayers map object by using the addControl function. The units of the first control are specified as metric. To create a scale line module which also shows imperial measurements, a second scale line control is added to the map with imperial units. OpenLayers takes care of listening out for changes on the map and updates the controls accordingly. Now we should see two scale lines on the map, but they are positioned on top of each other so we need some CSS to fix this.

Making it look good!

We can specify the CSS class names when creating the OpenLayers scale line controls. By doing so we can customise the default look of the scale line controls. Here we have added the class ‘scale-line-top’ to the metric control and ‘scale-line-bottom’ to the imperial control.