2

I need to convert distance from meters to units of EPSG 3857 in PostGIS. This is important for me to calculate a radius for ST_DWITHIN as I'm dealing with geometries. How can I do this?

2
  • 1
    3857 is in metres already
    – Ian Turton
    Jul 31, 2015 at 14:59
  • Yes, but meters in EPSG:3857 are badly distorted meters. Konrad, do you want to convert a circle with a radius in real world meters into an ellipse in EPSG:3857?
    – user30184
    Jul 31, 2015 at 15:48

1 Answer 1

3

As an approximation suitable for medium-small radii, use the cos() of the latitude to scale up the true distance to a "distance" that makes sense for your latitude in web mercator, as described here.

SELECT *
FROM mytable
WHERE ST_DWithin(
    ST_Transform(ST_SetSRID(ST_MakePoint(%lon, %lat), 4326), 3857),
    the_geom_webmercator,
    %radius / cos(%lat * pi()/180)
);

You only want to do this for small/medium radii because the scaling only makes sense at one latitude. The further you get from your reference latitude, the more wrong your radius gets. If you want a "perfect" result, you could pair this approach with a test on ST_DistanceSpheroid() to pare the results down to items exactly within the radius.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.