Skip to content

Instantly share code, notes, and snippets.

@ashaw
Created March 31, 2020 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashaw/2e7ab00819d92d9129571374aada80f0 to your computer and use it in GitHub Desktop.
Save ashaw/2e7ab00819d92d9129571374aada80f0 to your computer and use it in GitHub Desktop.
// https://projects.propublica.org/voting/static/vtile-bundle.js
import * as VectorTile from '@mapbox/vector-tile';
import * as Protobuf from 'pbf';
import * as Turf from '@turf/turf';
Math.radians = function(degrees) {
return degrees * Math.PI / 180;
};
export const TileQuery = {
TILE_BASE : "https://api.mapbox.com/v4/",
TILE_TOKEN : "YOURTOKEN",
tileToUrl : function(layer, obj) {
return this.TILE_BASE + layer + "/" + obj.z + "/" + obj.x + "/" + obj.y + ".vector.pbf?access_token=" + this.TILE_TOKEN
},
getTile : function(lng, lat, zoom) {
lat = Math.radians(lat);
const n = Math.pow(2.0, zoom);
const xtile = Math.floor(((lng + 180.0) / 360.0 ) * n)
const ytile = Math.floor((1.0 - Math.log(Math.tan(lat) + (1.0 / Math.cos(lat))) / Math.PI) / 2.0 * n)
return {z: zoom, x: xtile, y: ytile }
},
getDataForPoint : function(loc, layerSlug, layerName, cb) {
var pt = {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": loc
}
};
var tile_coords = this.getTile(loc[0], loc[1], 6);
var xhr = new XMLHttpRequest();
xhr.open(
/* method */ "GET",
/* file */ this.tileToUrl(layerSlug, tile_coords),
/* async */ true
);
xhr.responseType = "arraybuffer";
xhr.onload = function(evt) {
var pbf = new Protobuf(xhr.response);
var tile = new VectorTile.VectorTile(pbf);
var features = tile.layers[layerName];
var max = features.length;
var results = [];
for(var i=0; i < max; i++) {
var poly = features.feature(i).toGeoJSON(tile_coords.x, tile_coords.y, tile_coords.z);
var polyCentroid = Turf.centroid(poly);
var distance = Turf.distance(pt, polyCentroid, {units : 'miles'});
poly.properties.dist = distance;
poly.properties.centroid = polyCentroid;
results.push(poly);
}
results = results.sort(function(a, b) {
return a.properties.dist - b.properties.dist
});
cb(results)
}
xhr.send(null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment