gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:29:54 24 4
gpt4 key购买 nike

我在 Sequelize 中有一个 Location 模型

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 是否已经为我提供了查找距离的功能,还是我需要编写一个外部查询来找到它?

谢谢。

最佳答案

您不需要纬度和经度属性,它们将存储在您的位置属性中。要查找距离小于 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);
})

关于mysql - 使用 Sequelize 和 MySQL 的地理空间距离计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44675630/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com