Search code examples
sqlpostgresqlpostgis

POSTGIS Get nearest locations query


I am trying to get all offers located near a user within a distance of 100kms. The user shares the location and I query it in Offers Table - id, name, text, addressId (addressId is the foreign key)

Address Table - id, address, location.

Select Offers.id, Address.id 
from Offers, Address 
where 
  ST_Distance(
    ST_Transform( [12.9406589,77.6185572] ]::Geometry, 3857),
    ST_Transform( Address.location::Geometry, 3857) < 100 
  and Address.id = Offers.addressId

When I run the above query, it's throwing a syntax error:

Postgres syntax error near "]"

How else should I give the coordinates?


Solution

  • Have you tried combining ST_MakePoint and ST_SetSRID to create your point?

    SELECT Offers.id, Address.id 
    FROM Offers, Address 
    WHERE 
     ST_Distance(
       ST_SetSRID(ST_MakePoint(12.9406589,77.6185572),3857),
       ST_Transform( Address.location::Geometry, 3857)) < 100 AND 
    Address.id = Offers.addressId
    

    Note: The function ST_MakePoint expects the parameters as longitude,latitude, not the other way around.

    See also this related answer.