Reece Fowell
Reece Fowell

Reputation: 113

Predicates in Hibernate-Spatial + PostGIS to search within miles radius with Latitude / Longitude

I am trying to use Predicates in Hibernate-Spatial to search within a radius of X miles (user defined).

Though this sort of question has been asked before, only once before with Predicates and may not be current as it does not work. And I have to be able to use predicates and NOT HQL.

I found via another answer how to setup a Predicate for the WITHIN keyword of PostGIS but have been unable to get the query to run.

After setup at the end I state the error output and package versions.

Here is what I have in my schema:

CREATE EXTENSION Postgis;

CREATE TABLE "user" (
    id               bigint  NOT NULL,
    search_radius    int,
    latitude         double precision,
    longitude        double precision,
    location         geography(point, 4326),

    PRIMARY KEY (id)
);

In my model:

import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import org.hibernate.annotations.Type;

@Entity
@Table(name = "`user`")
public class User implements UserDetails {
    @Id
    private Long id;
    private Integer searchRadius = 125;
    private Double latitude;
    private Double longitude;
    @Column(name = "location", columnDefinition = "geography(Point, 4326)", nullable = true)
    @Type(type = "jts_geometry")
    private Point location;

    ...

    private void updateLocation() {
        if (latitude != null && longitude != null) {
            try {
                location = (Point) new WKTReader().read("POINT(" + latitude + " " + longitude + ")");
                location.setSRID(Location.SRID);
            } catch (ParseException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }
}

Where update location is called inside setters of lat / lng.

The predicate, which I obtained from Using JPA Criteria Api and hibernate spatial 4 together

import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;
import java.io.Serializable;
import javax.persistence.criteria.Expression;
import org.hibernate.jpa.criteria.CriteriaBuilderImpl;
import org.hibernate.jpa.criteria.ParameterRegistry;
import org.hibernate.jpa.criteria.Renderable;
import org.hibernate.jpa.criteria.compile.RenderingContext;
import org.hibernate.jpa.criteria.predicate.AbstractSimplePredicate;

public class WithinPredicate extends AbstractSimplePredicate implements Expression<Boolean>, Serializable {
    private final Expression<Point> matchExpression;
    private final Expression<Geometry> area;

    public WithinPredicate(CriteriaBuilderImpl criteriaBuilder, Expression<Point> matchExpression, Expression<Geometry> area) {
        super(criteriaBuilder);
        this.matchExpression = matchExpression;
        this.area = area;
    }

    public Expression<Point> getMatchExpression() {
        return matchExpression;
    }

    public Expression<Geometry> getArea() {
        return area;
    }

    public void registerParameters(ParameterRegistry registry) {
        // Nothing to register
    }

    @Override
    public String render(boolean isNegated, RenderingContext renderingContext) {
        StringBuilder buffer = new StringBuilder();
        buffer.append(" within(")
            .append(((Renderable) getMatchExpression()).render(renderingContext))
            .append(", ")
            .append(((Renderable) getArea()).render(renderingContext))
            .append(" ) = true ");
        String bo = buffer.toString();

        return bo;
    }
}

And creating the query, using the WithinPredicate and circle factory.

import com.xxxx.repository.WithinPredicate;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.util.GeometricShapeFactory;

@Service
class ... {
    public List<User> fetchFor(User user) {
        ...
        Geometry radius = createCircle(user.getLatitude(), user.getLongitude(), user.getSearchRadius());
        radius.setSRID(Location.SRID);
        p = b.and(p, new WithinPredicate(
            (CriteriaBuilderImpl) b,
            u.get(User_.location),
            new LiteralExpression<Geometry>((CriteriaBuilderImpl) b, radius)
        ));
    }

    private static Geometry createCircle(double x, double y, final double RADIUS) {
        GeometricShapeFactory shapeFactory = new GeometricShapeFactory();
        shapeFactory.setNumPoints(32);
        shapeFactory.setCentre(new Coordinate(x, y));//there are your coordinates
        shapeFactory.setSize(RADIUS * 2);//this is how you set the radius
        return shapeFactory.createCircle().getBoundary();
    }
}

Unfortunately, the error I get on the output is:

2016-09-09 14:03:30.862  WARN 56393 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 42883
2016-09-09 14:03:30.862 ERROR 56393 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: function st_within(geography, bytea) does not exist
  Hint: No function matches the given name and argument types. You might need to add explicit type casts.
  Position: 336

Hibernate-spatial version in gradle:

compile('org.hibernate:hibernate-spatial:5.0.9.Final')

I suspect the issue is due to perhaps the model / schema being set to a type of "Geography(Point, 4326)" but the shapeFactory creating a radius of type "Geometry(Point, 4326)".

Really appreciate any help on this. Thanks.

Upvotes: 1

Views: 2555

Answers (1)

Mike T
Mike T

Reputation: 43642

I've only read a portion of you question, however a few thing raised several red flags:

  • You need to flip the axis order to (X Y), or (longitude latitude)
  • ST_Within only exists for geometry types, not for geography
  • To find points within a region, don't create an imperfect buffered point
  • You will find ST_DWithin quicker and well supported for the geography type; for the radius, simply covert your miles to metres

Upvotes: 1

Related Questions