Search code examples
javageotoolsjts

Geotools - Create a point


I'm using GeoTools Java library for some geometric calculations. In my case, I'm using a shape file which contains all neighborhood multipolygons of a certain city. I would like to know for every possible coordinate in that city, at which neighborhood it corresponds to. So my approach is simply looping all over the neighborhood multipolygons and check whether the given point is within them or not. Here is a piece of the mentioned code:

public String getNeighborhoodId(Coordinates c){
    for(Feature f : neighborhoods){
        MultiPolygon m = (MultiPolygon) f.getProperty("geometry").getValue();

        GeometryBuilder builder = new GeometryBuilder(DefaultGeographicCRS.WGS84);
        Point p = builder.createPoint(c.getLat(),c.getLng());

        if(m.contains((Geometry) point)){
            return f.getProperty("neighborhoodId").getValue().toString();
        }   
    }
    return "";
}

Where neighborhoods are all the features previously read from the shape file. The problem is that at this line:

Point p = builder.createPoint(c.getLat(),c.getLng());

I am getting org.geotools.factory.FactoryNotFoundException: No factory of kind "PrimitiveFactory" found.

I simply followed the docs without much success (This approach does not work neither). Please notice that I'm using 9-SNAPSHOT version of GeoTools.

Any suggestions on how to get rid of this issue?


Solution

  • Well, I finally found out a possible solution. First of all, I must say I made a mistake, since my multipolygon points were in UTM and not in WGS84 format, so a previous conversion was required. On the other hand, I think I was using a wrong version of the GeometryFactory class, as before my refactoring process on my code, I was not able to instantiate it in the following way:

    public String getNeighborhoodId(Coordinates c){
        GeometryFactory geometryFactory = new GeometryFactory();
        String utm = converter.latLon2UTM(c.getLat(), c.getLng());
        Coordinate coords = new Coordinate(Double.valueOf(utm.split(" ")[2]),Double.valueOf(utm.split(" ")[3]));
        Geometry point = geometryFactory.createPoint(coords);
        for(Feature f : neighborhoods){
            MultiPolygon m = (MultiPolygon) f.getProperty("geometry").getValue();
            if(m.contains(point)){
                return f.getProperty("neighborhoodId").getValue().toString();
            }
        }
        return "";
    }