使用Sequelize和MySQL的地理空间距离计算器

4

我有一个Sequelize中的位置模型

var Sequelize = require('sequelize');

module.exports = function(sequelize, DataTypes) {
   var Location = sequelize.define('Location', {
      location_id: {
         type: Sequelize.STRING,
         primaryKey: true
      },
      location_code: {
         type: Sequelize.STRING,
         allowNull: true
      },
      location_name: {
         type: Sequelize.STRING,
         allowNull: true
      },
      latitude: {
         type: Sequelize.STRING,
         allowNull: true,
         defaultValue: null
      },
      longitude: {
         type: Sequelize.STRING,
         allowNull: true,
         defaultValue: null
      },
      location: {
         type: Sequelize.GEOMETRY('POINT'),
         allowNull: true
      }
   });
   return Location;
};

我通过输入经度和纬度来将其添加到位置中。
var location = { type: 'Point', coordinates: [latitude, longitude] };

我有一个路由器,它以经度和纬度作为参数。我需要找出提供的经纬度与“Locations”表中所有位置之间的距离。

我该怎么做?Sequelize是否已经为我提供了查找距离的函数,还是我需要编写外部查询来查找它?

谢谢。


需要使用特定的距离进行排序吗?还是可以使用任意距离? - sarikaya
你可以在这里找到答案:https://dev59.com/EVcP5IYBdhLWcg3wr74F#46438100 - sarikaya
2个回答

6

您不需要使用经度和纬度属性,它们将储存在您的位置属性中。 若要查找距离小于10000米的位置,请使用以下方法:

    var lat = parseFloat(json.lat);
    var lng = parseFloat(json.lng);
    var attributes = Object.keys(Location.attributes);
    var location = sequelize.literal(`ST_GeomFromText('POINT(${lng} ${lat})')`);
    var distance = sequelize.fn('ST_Distance_Sphere', sequelize.literal('location'), location);
    attributes.push([distance,'distance']);

    Location.findAll({
      attributes: attributes,
      order: 'distance',
      where: sequelize.where(distance, {$lte: 10000}),
      logging: console.log
    })
    .then(function(instance){
      return res.json(200, instance);
    })

出现错误 类型为 '{ $lte: 10000; }' 的参数无法分配给类型 'LogicType'。 @Edudjr - Md Alamin

3
 const { lat, lng, distance } = req.body.filter;

    Auction.findAndCountAll({
              include: [
                {
                  model: Property,
                  attributes: [
                    ['id', 'propertyID'],
                    ..............
                  ],
                  //lat lng and distance from angument
                  where: Auction.sequelize.and(
                    lat && lng && distance ? sequelize.where(
                      sequelize.literal(`6371 * acos(cos(radians(${lat})) * cos(radians(latitude)) * cos(radians(${lng}) - radians(longitude)) + sin(radians(${lat})) * sin(radians(latitude)))`),
                      '<=',
                      distance,
                    ) : null ,
                    {
                      status: 1,
                    }
                  ),

             //your code and logic
             .........
            }).then((result) => {
              ..........
            }).catch((err) => {
              ..........
            });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接