Skip to content

Instantly share code, notes, and snippets.

@hubgit
Last active December 16, 2015 21:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hubgit/5501688 to your computer and use it in GitHub Desktop.
Save hubgit/5501688 to your computer and use it in GitHub Desktop.
Postcode -> Location lookup using Ordnance Survey Linked Data APIs
$(function() {
var form = $("form");
var button = form.find("button[type=submit]");
var input = form.find("input[name=postcode]");
var output = form.find("output[name=location]");
var map = L.mapbox.map("map", "hubbox.map-u557d78b").setView([54, 0], 6);
var failed = function(data) {
button.html("Failed");
};
var lookup = function(event) {
event.preventDefault();
button.html("Loading…");
$.ajax({
type: "GET",
url: "http://beta.data.ordnancesurvey.co.uk/datasets/code-point-open/apis/search",
data: { output: "json", max: 1, query: input.val() },
dataType: "json",
error: failed,
success: function(data) {
if (!data.results.length) {
return failed();
}
fetch(data.results[0].link);
}
});
};
// can't use result.link directly, as the 303 redirect doesn't have CORS headers
// https://code.google.com/p/chromium/issues/detail?id=237490
var fakeRedirect = function(placeURI) {
var uri = placeURI
.replace(/^http:\/\//, "http://beta.")
.replace(/\/id\//, "/doc/");
return uri + ".json";
};
var fetch = function(placeURI) {
$.ajax({
type: "GET",
url: fakeRedirect(placeURI),
dataType: "json",
error: failed,
success: function(data) {
var item = data[placeURI];
var wardID = item["http://data.ordnancesurvey.co.uk/ontology/postcode/ward"][0].value;
var place = {
latitude: item["http://www.w3.org/2003/01/geo/wgs84_pos#lat"][0].value,
longitude: item["http://www.w3.org/2003/01/geo/wgs84_pos#long"][0].value,
name: data[wardID]["http://www.w3.org/2000/01/rdf-schema#label"][0].value
}
output.val(place.name);
map.setView([place.latitude, place.longitude], 13);
button.html("Lookup");
}
});
};
$("form").submit(lookup);
input.focus();
});
<!doctype html>
<meta charset="utf-8">
<!-- metadata -->
<title>Postcode -> Location via Ordnance Survey</title>
<!-- styles -->
<link rel="stylesheet" href="http://api.tiles.mapbox.com/mapbox.js/v1.0.1/mapbox.css">
<!-- form -->
<form>
<input type="text" name="postcode" placeholder="postcode">
<button type="submit">Lookup</button>
<output name="location" for="postcode"></output>
</form>
<!-- map -->
<div id="map" style="width:100%;height:600px;"></div>
<!-- scripts -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="http://api.tiles.mapbox.com/mapbox.js/v1.0.1/mapbox.js"></script>
<script src="app.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment