Jump to the following:

Ordnance Survey logo

Discover Ordnance Survey

Site Search

Adding a Postcode Search

The following example allows entry of a correctly spelt postcode e.g. S9 5NF or S95NF or a postcode sector e.g. S9. We are going to build on displaying a marker tutorial. In this tutorial we created an HTML document with all the appropriate tags and included a DIV tag which gave instructions on how to display the map. The heavy lifting is all done within the javascript section (between the script…/script tags). The instructions in this document will deal with this core of the code. Essentially we will be replacing the content of displaying a marker tutorial script tags, with the following:


<script type="text/javascript">
var osMap;
function init()
{
osMap = new OpenSpace.Map('map');
var postcodeService = new OpenSpace.Postcode();
postcodeService.getLonLat("S9 5NF", onResult);
}
function onResult(postcodeCentre)
{
osMap.setCenter(postcodeCentre, 10);
}
</script>

Let's break this up

We start a script tag to contain our code.


<script type="text/javascript">

Then we create a map object variable, osMap.


var osMap;

Now we define our init function.


function init()
{

Then create a new OS OpenSpace map object and pass it our 'map' element id. This is the HTML div that will hold the map.


osMap = new OpenSpace.Map('map');

Then we start up the postcode service which is where we search using the geometry of Code-Point


var postcodeService = new OpenSpace.Postcode();

The postcode service is searched to see if there is a match and if there is a MapPoint is sent to a function (onResult in this case).


postcodeService.getLonLat("S9 5NF", onResult);

Finally, if the postcode or sector was found the map is centred at its centre and at a zoom level of our choosing.


function onResult(postcodeCentre)
{
osMap.setCenter(postcodeCentre, 10);
}

The full code can be found below:


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Open Space Tutorial 5</title>
<script type="text/javascript" src="http://openspace.ordnancesurvey.co.uk/osmapapi/openspace.js?key=insert_your_api_key_here"></script>
</head>
<body onload="init()">
<script type="text/javascript">
var osMap;
function init()
{
osMap = new OpenSpace.Map('map');
//initialise the postcode service into a variable
var postcodeService = new OpenSpace.Postcode();
//pass our input, in this case 'hard-wired', to a function
postcodeService.getLonLat("S9 5NF", onResult);
}
function onResult(postcodeCentre)
{
/*if found, a MapPoint is passed into this function and the map is
centered on it at
zoom level 10 */
osMap.setCenter(postcodeCentre, 10);
}
</script>
<h1>Find location by postcode or postcode sector</h1>
<div id="map" style="width: 500px; height: 300px; border: 1px solid black;"></div>
</body>
</html>

For general enquiries, complaints, feedback or suggestions, email: customerservices@ordnancesurvey.co.uk or call us on 08456 05 05 05