nodejs+postgis实现搜周边

利用nodejs搭建服务器,并连接PostgreSQL数据库,利用前端传过来的中心点坐标和搜索半径,进行空间查询,实现简单的搜周边,下面是实现流程和nodejs的代码:

nodejs+postgis实现搜周边_第1张图片

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();
                }
            });
        });
    }
);

 

你可能感兴趣的:(postgis)