Postcode Anywhere Mapping Services
There’s nothing like a good map. Location data is one thing, but we all like to see it mapped out do that we can effectively visualise it.
Luckily Postcode Anywhere’s mapping services allow you to display your data and services in a clean, efficient and easy to use interface; and in this tutorial we are going to take a look at just how that is done.
Step 1: Setting the Page
Ok, so we’ve decided we want a mapping service on our website. The first thing we are going to need is a page on which to place the map. To keep it simple in this example, we're just going to create a blank HTML page to display my map. Here is a ‘Hello World’ example of the PCA mapping service:
<html>
<head>
<script src="http://services.postcodeanywhere.co.uk/maps/?Key=AA11-AA11-AA11-AA11&Version=1.3" type="text/javascript"></script>
</head>
<body>
<div id="map" style="height:100%; width:100%"></div>
<script type="text/javascript">
var map = new pcaMap(document.getElementById("map"));
map.CentreAndZoom(380000, 260000, 1000);
</script>
</body>
</html>
Just replace the AA11’. With your own key, load up the page and you should see a fully rendered PCA map!
Step 2: Zooming
As you can see we’ve already used one of the mapping methods (CentreAndZoom) to initialise the map at a particular location, and set an original zoom level.
That’s great, but when I use a map online, I always like to have both a zoom control and to be able to zoom using the mouse wheel.
In order to enable this on the maps we add in another two methods directly after the 'CentreAndZoom':
map.CreateZoomControl();
map.EnableMouseScroll();
These methods do pretty much exactly what they say on the tin, CreateZoomControl creates a visual zoom control on the map, and EnableMouseScroll enables zooming in and out using the mouse wheel.
The full list of zoom related methods are as follows:
-
CreateZoomControl()
Creates a zoom control on the map to allow zooming.
-
CentreAndZoom(easting, northing, zoom)
Initialises the map view to a set location and zoom level.
-
ZoomMap(delta)
Zooms the map by the provided zoom level index delta. Supply a negative value to zoom out.
-
EnableMouseScroll()
Enables the mouse scroll wheel to be used to zoom in and out of the map.
-
DisableMouseScroll()
Disables zooming with the mouse scroll wheel.
Step3: Markers
A maps great, but it’s no good if you can’t point things out on it. This is achieved by using Markers.
To demonstrate, and to show you how the markers look add the following into your code:
map.CreateMarker(380000, 260000);
You should now have a single marker added to your map.
The CreateMarker method can also have an optional options parameter, the options are as follows:
-
Name: Specifies mouse over alt text and title for the marker.
-
Colour: Changes the colour of the marker. Options are basic colours such as red, green, blue, yellow, orange, purple, pink, black, white.
-
Image: Allows a custom image to be used as a marker.
-
Height: The height of the image.
-
Width: The width of the image.
-
Top: The offset in pixels from the top of the image to the marker point.
-
Left: The offset in pixels from the left side of the image to the marker point.
So a marker with a different colour and mouse over name would look like this:
map.CreateMarker(380000, 260000, { Name: ‘Postcode Anywhere’, Colour: ‘orange’ });
We can also add a popup box to our pin to display more information. This is done by using a few other methods as laid out below:
var marker = map.CreateMarker(381472, 259318, { Name: "Postcode Anywhere", Colour: "orange" });
marker.SetInfo("Enigma House
Moseley Road, Hallow, Worcester.
WR2 6NJ", 200, 200);
marker.AddListener(function() { marker.ShowInfo() });
This uses the SetInfo method to assign the information to the marker, and the ShowInfo method to display it. The AddListener method adds an OnClick event to the marker, from which we can
display the information.
The full list of methods relating to markers is as follows:
-
CreateMarker(easting, northing, options)
Creates a new marker at the given location. Accepts optional options object.
-
RemoveMarker(marker)
Removes the specified marker from the map
-
ClearMarkers()
Clears all markers from the map.
-
SetMarkerInfo(marker, content, width, height, options)
Sets the info to be displayed in the callout window. Takes a reference to a marker, content as HTML and a size.
-
ShowMarkerInfo(marker)
Displays the callout window for a given marker.
-
CloseInfoWindow()
Closes any callout window currently open.
Step 4: Basic Routes and Shapes
Often you will want to use a mapping service to display a planned out route, or a particular shape.
The most basic way to do this using Postcode Anywhere’s mapping service is to use the AddRoute or AddShape:
-
AddRoute(points, options)
Sets the route to be drawn on the map. The Map will only draw one route at a time. Points should be provided as an array of arrays containing easting and northing for each point. Accepts optional options object.
-
AddShape(points, solid, options)
Adds a shape to be drawn on the map. Points should be provided as an array of arrays containing easting and northing for each point. Solid should be provided as a Boolean value indicating whether or not the shape should be drawn as a solid shape and filled.
So for example you can add a basic route like this:
var _points = [[[408525, 257654], [408745, 257375], [408786, 257748], [408312, 257985]]];
map.AddRoute(_points, { Colour: "#3333CC", Weight: 5 });
(It’s quite a small route, you might want to centre and zoom in on the map to see it, try this:
map.CentreAndZoom(408525, 257654, 2);
or you can add a basic shape like this:
var _points = [[[408125, 257654], [408745, 257375], [408786, 257748], [408312, 257985]]];
map.AddShape(_points, true, { Colour: "#CC3333", Opacity: 0.5 });
(You might want to try the centre and zoom again.)
So, that’s all very well if you know all the points of your route before hand, but lets face it, who knows all the curves and turns on the road ahead. Luckily we have a routing service that you can call from the map page and use to plot your routes automatically.
This is a bit more code heavy so I’m going to break it down into a series of code snippets.
Snippet1: Setting your parameters
Ok, so in order to plan a route your obviously going to need a start and end point, and these need to be declared as variables within your code.
We're going to hard code our start and end points into our page, but you’ll probably want to pull them in from a text box, or other input method.
So, in this example we declare our variables like this:
var _start = "WR2 6NJ", _finish = "B49 5HH";
Snippet2: Building the request
function route() {
var _req = "/DistancesAndDirections/Interactive/DirectionsAndLines/v1.00/json.ws?";
_req += "&Key=" + escape("AA11-AA11-AA11-AA11");
_req += "&Start=" + escape(_start);
_req += "&Finish=" + escape(_finish);
_req += "&DistanceType=Fastest";
_req += "&LineStyle=JSEastNorth";
_req += "&CallbackFunction=routeEnd";
fetch(_req);
}
The function above will put all the parameters of the web service call together, notice out _start and _finish variables being used to supply the start and end points, and remember to add your own key.
On completion this function calls fetch(_req).
Snippet3: fetch
function fetch(request) {
var _script = document.getElementById("pcaScript"),
_head = document.getElementsByTagName("head").item(0);
if (_script)
try { _head.removeChild(_script) } catch (e) { };
_script = document.createElement("script");
_script.src = "http://services.postcodeanywhere.co.uk" + request;
_script.type = "text/javascript";
_script.id = "pcaScript";
_head.appendChild(_script);
}
The code above takes the parameters we created in route() and uses them as part of a web service call to return an array of points to plot the route with.
Snippet4: Display
You may have noticed that one of the parameters we used in route() was &CallbackFunction=routeEnd. This means that the response from fetch() will be in the form of json padded with the function name routeEnd. This allows the json response to be fed directly into a pre-existing routeEnd function, hence we need to have one on our page:
function routeEnd(response) {
if (response.length == 1 && typeof (response[0].Error) != 'undefined')
alert(response[0].Description);
else {
if (response.length == 0)
alert("Unable to calculate route");
else {
map.ClearRoutes();
map.ClearMarkers();
map.ClearListeners();
var _points = [],
_segment = 0;
for (var i in response) {
response[i].Line = eval(response[i].Line);
if (response[i].Line)
_points = _points.concat(response[i].Line);
}
map.AddRoute(_points, { Colour: "#CC33BB" });
var _startpoint = _points[0],
_endpoint = _points[_points.length - 1],
_distance = Math.sqrt(Math.pow(_startpoint[0] - _endpoint[0], 2) + Math.pow(_startpoint[1] - _endpoint[1], 2)),
_mapsize = Math.min(map.Properties.Height, map.Properties.Width),
_levels = map.GetZoomLevels();
var _startmarker = map.CreateMarker(_startpoint[0], _startpoint[1], { Colour: "green" }),
_finishmarker = map.CreateMarker(_endpoint[0], _endpoint[1], { Colour: "red" });
}
}
}
This function does several things. Firstly it checks the length and format of the response to see if there has been an error in the request. If no error has occurred it clears and pre-existing items on the map, creates the variable _points as an empty array, and then populates _points with the points from the response of fetch().
This array of array’s (_points) is then used with the AddRoute method to create the line and display the route. Finally it reads the first and last point in _points and creates a green marker for the start point and a red marker for the end point.
And you thought route planning was hard!