Skip to main content
3 of 3
naming
Vince
  • 20.3k
  • 16
  • 48
  • 65

Use ST_DWithin on WGS84 geometry data

I've just used osm2pgsql to import osm data to a PostGIS database, using lat/long option to store it in WGS84 projection. I would like to use ST_DWithin to select nodes close to a random point. When I try that directly on the WGS84 data it returns wrong results but works if I reproject it in Web Mercator. What am i missing to avoid the reprojection?

SELECT ST_AsText(way),
       ST_X(ST_AsText(way)) as X,
       ST_Y(ST_AsText(way)) as Y,
       railway
  FROM planet_osm_point
 WHERE railway IS NOT NULL AND
       ST_DWithin(ST_Transform(way, 3785),
                  ST_Transform(ST_SetSRID(ST_MakePoint(-1.631560, 48.107485), 4326), 3785),
                  500)
 LIMIT 1000;

Mercator projection output

SELECT ST_AsText(way),
       ST_X(ST_AsText(way)) as X, 
       ST_Y(ST_AsText(way)) as Y,
       railway
  FROM planet_osm_point 
 WHERE railway IS NOT NULL AND
       ST_DWithin(way, ST_SetSRID(ST_MakePoint(-1.631560, 48.107485), 4326), 500)
 LIMIT 1000;

WGS84 projection output

As you can see the outputs from WGS84 projection aren't even close to the point I'm lookin at and I can't figure out why when I am using the same geometry type for ST_DWithin. Is there a step I'm missing? (also I am not showing all of the results here, the Web Mercator projection gets me about 154 results, while WGS84 projection goes beyond 1000)