Skip to content

Instantly share code, notes, and snippets.

@ajmas
Created April 4, 2016 21:03
Show Gist options
  • Save ajmas/d9e323ef5af40cf469934fa319e16a34 to your computer and use it in GitHub Desktop.
Save ajmas/d9e323ef5af40cf469934fa319e16a34 to your computer and use it in GitHub Desktop.
// depends on turf and having a copy of the countries.gejson file for the value of the countryOutlines
// see: https://github.com/johan/world.geo.json as one source
findCountryName (latlon) {
var features, i, j, poly;
var point1 = turf.point([latlon[1], latlon[0]]);
if (this.countryOutlines) {
features = this.countryOutlines.features;
for (i=0; i<features.length; i++) {
if ( features[i].geometry.type === 'MultiPolygon' ) {
for (j=0; j<features[i].geometry.coordinates.length; j++) {
poly = turf.polygon(features[i].geometry.coordinates[j]);
try {
if (turf.inside(point1, poly)) {
return features[i].properties.name;
}
} catch (e) {
// typically happens due to a geometry issue
console.error(e, features[i].id, j);
}
}
} else if ( features[i].geometry.type === 'Polygon' ) {
poly = turf.polygon(features[i].geometry.coordinates[0]);
if (turf.inside(point1, poly)) {
return features[i].properties.name;
}
} else {
console.error('unknown geometry type: ' + features[i].geometry.type);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment