I am trying to take a lat/lon and find which country the lat/lon is located in.
Below is a boilerplate of code I found to accomplish this, which was found in this post (Reverse Geocode latitude longitude with Geotools using Natural Earth Shapefiles in Java )
SpatialIndexFeatureCollection countries;
final static FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();
final static public String countryFile ="/data/natural_earth/10m_cultural/10m_admin_0_countries.shp";
public SimpleGeoCoder() throws IOException {
// load the country shapefile
URL countryURL = DataUtilities.fileToURL(new File(countryFile));
HashMap<String, Object> params = new HashMap<>();
params.put("url", countryURL);
DataStore ds = DataStoreFinder.getDataStore(params);
if (ds == null) {
throw new IOException("couldn't open " + params.get("url"));
}
Name name = ds.getNames().get(0);
countries = new SpatialIndexFeatureCollection(ds.getFeatureSource(name).getFeatures());
}
GeometryFactory gf = new GeometryFactory();
Point london = gf.createPoint(new Coordinate(0.0, 51.0));
public SimpleFeatureCollection lookup(Point p) {
Filter f = ff.contains(ff.property("the_geom"), ff.literal(p));
return countries.subCollection(f);
}
SimpleFeatureIterator itr = features.features();
try {
while (itr.hasNext()) {
SimpleFeature f = itr.next();
System.out.println(f.getAttribute("NAME"));
}
} finally {
itr.close();
}
Most of the time this solution works, however there seems to be cases where a lat/lon will not be found within the Natural Earth shapefiles. A perfect example would be for the city of Miami Florida (25.761681, -80.191788) when using the shapefile "10m_cultural/10m_admin_0_countries.shp".
My original solution was to use the shapefile "110m_cultural/110m_admin_0_countries.shp" the Miami example will be fine. However I have found a few other examples which occur within the 110m shapefile and I don't know what the solution is. Do I use both the 10m and the 110m shapefiles? Or is there some setting or something else I need to do to accurately solve this issue?