secret
Last active

Using KDTree for geospatial lookups (slightly experimental) (this is an untested example)

  • Download Gist
example.html
Liquid
1 2 3 4 5 6 7 8 9 10 11 12 13 14
<!Doctype html>
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/zepto/1.0rc1/zepto.min.js"></script>
<script src="script.js"></script>
</head>
 
<a id="button" href="#">
<p>I AM A BUTTON</p>
</a>
 
<script type="text/javascript" src="kdtree.js"></script>
</body>
</html>
script.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
var storeTree = [];
 
var getNearest = function(location) {
 
nearest = storeTree.getNearestNeighbour({
x: location.coords.longitude,
y: location.coords.latitude
});
 
//if you just more than one result then use this function instead - returns an array of objects
/**
* storeTree.getNearestNeighbours({
* x: location.coords.longitude,
* y: location.coords.latitude
*}, 1); //Number of results you want returned - they are always returned as an array
*/
 
//data/records/XXX/.json is arbitary path
$.getJSON('data/records/' + nearest.id + '.json',
function(returnedObject) {
//Do something with the returned object
});
 
};
 
var errorFunc = function(err){
console.log(err);
}
 
$(document).ready(function () {
 
//Load up the index of stores - this is an odd way to do it
$.getJSON('data/records/index.json', function(data){
if(Array.isArray(data)) {
storeTree = new KDTree(data);
} else {
storeTree = new KDTree([]);
storeTree.rootNode = data.rootNode;
}
});
 
$('#button').click(function () {
navigator.geolocation.getCurrentPosition(getNearest, errorFunc, { enableHighAccuracy:true, timeout:1200, maximumAge:0 });
 
})
});

TODO - stop this using zepto if we can (or make another version which doesn't use it)
TODO - Move out kdtree into a gh repo

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.