最近项目开发项目。小程序增加了搜索附近的任务功能。原来使用redisGEO实现了此功能。此后增加需求按条件查询附近的功能。想看看使用MySQL去实现该需要。经过分析和查询后可以有两种实现方案,在此记录下。
方案一
搜索附近功能时,都会指定一个搜索的距离。假设我们设定的10公里的范围,已有当前的经纬度,数据库记录的任务也记录每个工作的经纬度。我们可以引用spatial4j第三方类包,算出当前坐标的最大经纬度和最小的经纬度。然后搜索范围内的任务即可查询出来。
伪代码示例
/**
* 利用开源库计算外接正方形坐标
* @param distance 查询范围
* @param userLng 用户经度
* @param userLat 用户纬度
* @return
*/
private Rectangle getRectangle(double distance, double userLng, double userLat) {
return spatialContext.getDistCalc().calcBoxByDistFromPt(
spatialContext.makePoint(userLng, userLat), distance * DistanceUtils.KM_TO_DEG, spatialContext, null);
}
//
@GetMapping("/nearby1")
public String nearBySearch1(@RequestParam("distance") double distance,
@RequestParam("userLng") double userLng,
@RequestParam("userLat") double userLat) {
Rectangle rectangle = getRectangle(distance, userLng, userLat);
//获取位置在正方形内的所有用户
List<Task> taskList = userMapper.selectUser(rectangle.getMinX(), rectangle.getMaxX(), rectangle.getMinY(), rectangle.getMaxY());
return JSON.toJSONString(taskList );
}
///
<select id="selectUser" >
SELECT * FROM task
WHERE 1=1
and (longitude BETWEEN #{minlng} AND #{maxlng})
and (latitude BETWEEN #{minlat} AND #{maxlat})
</select>
方案二
使用MySQL的自带函数st_distance_sphere进行查询,也可以实现该功能
select t1.taskNo,t1.lon,t1.lat, round(
st_distance_sphere(
point('117.2563', '38.45662'),
point(`lon`, `lat`))) distance from task t1 where t1.name = '111'
方案三
使用redisGeo进行查询。具体方法请看redisGEO实现距离排序