Skip to content

Instantly share code, notes, and snippets.

@ianchanning

ianchanning/app.js

Forked from hubgit/app.js
Created Feb 4, 2014
Embed
What would you like to do?
$(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