nodejs+postgis实现搜周边
2024-10-21 09:26:32
利用nodejs搭建服务器,并连接PostgreSQL数据库,利用前端传过来的中心点坐标和搜索半径,进行空间查询,实现简单的搜周边,下面是实现流程和nodejs的代码:
app.post('/tosearcharound', multipartMiddleware, function (req, res) {
var queryData = "";
req.on('data', function (strChunk) {
queryData += strChunk;
});
req.on('end', function () {
console.log('数据接收完毕');
//解析出客户端提交的信息中的参数,进行postgres查询
var querystring = require("querystring");
var params = querystring.parse(queryData);
var pointx = params['pointx'],
pointy = params['pointy'],
searchRadius = params['searchRadius']; console.log(pointx+" "+pointy+" "+searchRadius); //利用客户端传过来的参数做查询,将查询结果返回到客户端
//加载相应的模块,不同的数据库使用不同的模块
var pg = require('pg');
//构造连接数据库的连接字符串:"tcp://用户名:密码@ip/相应点数据库名"
var conString = "tcp://postgres:post@localhost:5432/projectdb";
//构造一个数据库对象
var client = new pg.Client(conString); //连接数据库,连接成功,执行回调函数
client.connect(function (error, results) {
if (error) {
console.log("could not connect to postgres" + error.message);
client.end();
return;
}
console.log("Client connect is ok.\n");
});
var querystring = "select st_astext(the_geom) from poi_beijing where ST_DWithin(ST_Transform(the_geom,26986),ST_Transform(ST_Geometryfromtext('point('||" + pointx + "||' ' ||" + pointy + "||')',4326),26986)," + searchRadius + ")";
console.log(querystring);
//执行相应点sql语句
client.query(querystring, function (error, results) {
console.log("in callback function.\n");
//console.log(results);
//console.log(results.rowCount);
if (error) {
console.log("error");
console.log('GetData Error:' + error.message);
client.end();
return;
}
if (results.rowCount > 0) {
console.log(results);
//callback(results)
//指定为json格式输出
res.writeHead(200, {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
}); //先将results字符串内容转化成json格式,然后响应到浏览器上
res.write(JSON.stringify(results, undefined, 3));
res.end();
}
});
});
}
);
最新文章
- mysql workbench如何把已有的数据库导出ER模型
- 【转载】如何用IntelliJ IDEA 14 创建Web项目
- MyBatis学习(二)、SQL语句映射文件(1)resultMap
- C++自问自答
- Java菜鸟学习 Script 脚本语言(简介)
- Conntect Bluetooth devices in iOS.
- 修复eclipse中使用mave update project后JRE都变成1.5的问题
- Noi2011 : 智能车比赛
- 5月23日 JavaScript练习:累加求和
- (easy)LeetCode 191.Number of 1 Bits
- PHP设计模式之装饰器模式
- nodejs中使用递归案例
- 修改linux文件权限命令:chmod 【转载】
- lintcode 453 将二叉树拆成链表
- 34.Linux-printk分析、使用prink调试驱动
- 详细介绍Ubuntu 16.04系统环境安装Docker CE容器的过程
- C#俄罗斯方块小游戏程序设计与简单实现
- [UE4]记录瞬移目标点
- 旅游吧!我在这里 ——旅游相册POI搜索:找回你的足迹
- Firefox、Chrome、IE9、IE8、IE7、IE6等浏览器HTTP_USER_AGENT汇总