db-mongo-near

  1. 需求

    • 判断某个位置是否偏移预定路线 比如离开指定路线 x 米。
  2. 已有数据

    • spring boot 2.7.3、mongo 数据库 4.2
    • 高德路径规划 根据返回的数据整理。
    • 一个实时的位置点
  3. 实现思路

    • 自己可实现 根据算法点到直线的距离(麻烦且耗时)
    • mongo 的 near 函数
    • 以实时位置点为圆心 x 为半径画圆 判断指定的路线和圆是否有重叠 有的话说明未偏移 反之偏移
  4. 实操

    • 数据结构
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      package com.example.mongo;

      import lombok.Data;
      import org.springframework.data.mongodb.core.geo.GeoJsonMultiLineString;
      import org.springframework.data.mongodb.core.index.GeoSpatialIndexType;
      import org.springframework.data.mongodb.core.index.GeoSpatialIndexed;
      import org.springframework.data.mongodb.core.mapping.Document;

      @Data
      @Document("route")
      public class Route {
      private String name;
      @GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE)
      private GeoJsonMultiLineString lines;
      }
  5. $nearSphere 函数的方式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     db.route.find({
    lines: {
    $nearSphere: {
    $geometry: {
    type : "Point",
    coordinates : [ 116.480891, 39.98937 ]
    },
    $minDistance: 0,
    $maxDistance: 30
    }
    }
    })

    解释

    route Collection 集合名
    lines 需要匹配的轨迹是多line的数组 当然也可以是任何 GeoJSON
    geometry 用于指定与其他 GeoJSON 一起参与运算

  6. $geoWithin + $centerSphere

    1
    2
    3
    4
    5
    {
    <location field>: {
    $geoWithin: { <shape operator>: <coordinates> }
    }
    }

    shape operator 运算符包含 $box,$polygon,$center,and$centerSphere

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    db.route.find(
    {
    "lines": {
    "$geoWithin": {
    "$centerSphere": [
    [
    129.0,
    49.98937
    ],
    0.000004703567828662194
    ]
    }
    }
    }
    )

    解释

    route Collection 集合名
    lines 需要匹配的轨迹是多line的数组 当然也可以是任何 GeoJSON
    0.004703567828662194 这个很关键 这个圆的半径以弧度测量
    1(km/千米) = 1/6378.137(弧度) 1(mi/英里) = 1/3963.191(弧度)

作者

lizhongyuan3

发布于

2022-09-16

更新于

2022-09-17

许可协议

评论