使用Sequelize和MySQL的地理空间距离计算器
作者:互联网
我在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] };
我有一个将纬度和经度作为参数的路由器.我需要在“位置”表中找出所提供的经度/纬度与所有位置之间的距离.
我该怎么做呢? 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);
})
标签:sequelize-js,geospatial,latitude-longitude,mysql 来源: https://codeday.me/bug/20191025/1932297.html