如何查询postgres数据库以获取特定坐标10公里半径内的所有点

How to query a postgres database to get all points within a 10km radius of certain coordinates

我有一个商店数据库,在该数据库中我保存了这些商店的坐标。我想获取 10 公里半径内的商店列表,但是我不确定如何编写 Postgres 查询,因为我使用的是 Postgres 数据库。

我的数据库:

我正在尝试将查询添加到 springboot 地理定位微服务中:

存储库代码:

@Repository
public interface SellerGeolocationRepository extends CrudRepository<Seller_Geolocation, Long> {

    @Query(value="SELECT * FROM seller_geolocation_ms WHERE 
   // get coordinates that are in the vicinity
", nativeQuery = true)
        public Set<Seller_Geolocation> findAllSellersInRange(double longitude, double latitude);

    }

卖家对象:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "seller_geolocation_ms")
public class Seller_Geolocation {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private static final long serialVersionUID = 2L;

    private double latitude;
    private double longitude;
    private String country;
    private String city;
    private String zipCode;
    private String town;
    private String address;
    private Long sellerId;
}

您可以使用 haversine 公式,使用您当前的坐标 (target_latitude_deg/longitude) 和列名称 (latitude_deg, longitude_deg),两者均以度数表示

SELECT * 
FROM myTable
WHERE acos(
       sin(radians(target_latitude_deg)) 
         * sin(radians(latitude_deg)) 
       + cos(radians(target_latitude_deg)) 
         * cos(radians(latitude_deg)) 
         * cos( radians(target_longitude_deg)
           - radians(longitude_deg))
       ) * 6371 <= 10;

或者,查看 PostGIS 扩展

SELECT * 
FROM MyTable 
WHERE ST_Dwithin(geom, st_point(target_longitude, target_latitude,10000);

看看 Postgres earthdistance, ther's also an example mentioned here 但是,您可以使用具有丰富地理空间功能的Postgis。 如果您想在业务逻辑上进行计算,请使用上面@JGH 回答中解释的 Haversine 公式。

为此,您需要安装 postgis:

brew install postgis

之后您需要在您的 postgres 数据库上安装 postgis "seller_geolocation_ms":

   1. $ sudo -i -u postgres
   2. $ psql
   3. postgres=# \c seller_geolocation_ms;
   4. seller_geolocation_ms=# CREATE EXTENSION postgis;
   5. \q

完成这些步骤后,应该在您的数据库上安装 postgis。那么接下来要做的就是像这样在你的 Springboot 存储库界面上编写查询:

@Repository
public interface SellerGeolocationRepository extends CrudRepository<Seller_Geolocation, Long> {

    @Query(value="SELECT * FROM seller_geolocation_ms WHERE ST_DWithin(cast(seller_geolocation_ms.location as geography),ST_SetSRID(ST_Point(?2, ?1),4326), 10000);", nativeQuery = true)
    public Set<Seller_Geolocation> findAllSellersInRange(double longitude, double latitude);

}

要更深入地了解如何 ST_DWithin,请遵循此 link :here