使用Node.JS进行谷歌地图定位

此系统需求为在浏览器页面中输入人名,提交到后台在数据库中查找地址,并将地址传递到浏览器页面后调用谷歌地图api,进行地址解析并定位标注(浏览器页面中需编写一个ajax调用)

服务器端代码server.js


var mysql      = require('mysql');
var pool = mysql.createPool({
  connectionLimit : 10,
  host     : 'us-cdbr-iron-east-02.cleardb.net',
  user     : 'bd6acx3bd0c01b',
  password : 'f4ba4af2',
  database : 'heroku_33a4ds48168f4x3',
  port:3306
});

var fs = require('fs');
var http = require("http");
const url = require("url");
const querystring = require("querystring");
const server = http.createServer((request, response) => {    
    console.log(request.url);
    if (request.url.startsWith("/get?")) {        
        //数据处理
        const obj = url.parse(request.url, true)
        var peopleName=obj.query['peoplename'].toString()
        var arrName = peopleName.split(" ")
        let firstname=''
        let middlename=''
        let lastname=''
        let nameNum=0 //middlename会为空值,进行计算
        let index=[]
        let j=0
        for(let i=0;i<arrName.length;i++)
        {
            if(arrName[i]!='')nameNum+=1
            if(arrName[i]!='') {
                    index[j] = i
                    j++
                }
        }

        if(nameNum==2)
        {
            firstname=arrName[index[0]].toString()
            lastname=arrName[index[1]].toString()
        }
        else
        {
            firstname=arrName[index[0]].toString()
            middlename=arrName[index[1]].toString()
            lastname=arrName[index[2]].toString()
        }

        var  userAddSql_Params = [firstname, middlename,lastname];
        
        pool.query('SELECT addrbusiness,city,state FROM peopleinfo where firstname=? and middlename=? and lastname=?',userAddSql_Params, function (error, results) {
          //if (error) throw error;
          if (error)  return;
          console.log('The addr is: ', results[0].addrbusiness +' ' + results[0].city+ ' ' + results[0].state);

          response.writeHead(200,"ok",{
            "Content-type":"application/x-javascript",
            "Access-Control-Allow-Origin":(request.url,
            "Access-Control-Allow-Headers":"damu",
            "Access-Control-Allow-Methods":"PUT,DELETE,POST",
            "Access-Control-Max-Age":"10"
        })
        
        //    if (item.hasOwnProperty("name")) {     }
        //var str = JSON.stringify(url.parse(request.url, true).query);
        response.write(results[0].addrbusiness +' ' + results[0].city+ ' ' + results[0].state);
        response.end();
        });


    } else if (request.url.startsWith("/post")) {



    } else {
       // response.writeHead(500, "Invalid Request", {"Content-Type": "text/html; charset=utf-8"});
       // response.end("无效请求");
        // 解析请求,包括文件名
       var pathname = url.parse(request.url).pathname;

       // 输出请求的文件名
       console.log("Request for " + pathname + " received.");

       // 从文件系统中读取请求的文件内容
       fs.readFile(pathname.substr(1), function (err, data) {
          if (err) {
             console.log(err);
             // HTTP 状态码: 404 : NOT FOUND
             // Content Type: text/html
             response.writeHead(404, {'Content-Type': 'text/html'});
          }else{
             // HTTP 状态码: 200 : OK
             // Content Type: text/html
             response.writeHead(200, {'Content-Type': 'text/html'});

             // 响应文件内容
             response.write(data.toString());
          }
          //  发送响应数据
          response.end();
       });
    }
})

server.listen(process.env.PORT || 8080 , () => {
    //console.log(`server starting at ${config.host}:${config.port}`)
    console.log(`server starting at 127.0.0.1:8080`)
})

 index.html页面代码

<!DOCTYPE html>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&key=AIqfSyCbzKZLTVlEJwsmQQy_RKSyFczidmpw63M&sensor=SET_TO_TRUE_OR_FALSE"></script><script>

    window.onload = ()=>{
        const peoplename = document.querySelector("#address");
        const ajaxBtn = document.querySelector("#submit");
        ajaxBtn.addEventListener("click",(ev)=>{
            ev = ev||event;
            ev.preventDefault();
            const query = peoplename.value;
            const url = "https://mynodejsmap.herokuapp.com"+`/get?peoplename=${query}`;
            //const url = "http://127.0.0.1:8080"+`/get?peoplename=${query}`;
            makeRequest("GET",url)
        })

        function makeRequest(method,url) {
         const   httpRequest = new XMLHttpRequest();

            if (!httpRequest) {
                alert('Giving up :( Cannot create an XMLHTTP instance');
                return false;
            }
            httpRequest.onreadystatechange = ()=>{
                if (httpRequest.readyState === XMLHttpRequest.DONE) {
                    if (httpRequest.status === 200 || httpRequest.status === 304) {
                        console.log(httpRequest.status.toString())
                        console.log(httpRequest.responseText)                    
                        //实例化Geocoder服务
                        var geocoder = new google.maps.Geocoder();
                        //1.地理解析过程
                        //请求数据GeocoderRequest为address
                        geocoder.geocode({ address: httpRequest.responseText }, function geoResults(results, status) {
                            //这里是回调函数
                            //状态为Ok说明正确
                        if (status == google.maps.GeocoderStatus.OK) {                           
                            //获取解析后的经纬度
                            //alert('result:' + results[0].geometry.location);
                            var latlng = new google.maps.LatLng(results[0].geometry.location.latitude,results[0].geometry.location.longitude);
                            var myOptions = {
                                              zoom:16,                             //设定缩放倍数
                                              center:latlng,                       //地图中心设定为指定的坐标点
                                              mapTypeId:google.maps.MapTypeId.ROADMAP     //指定地图类型
                                            };
                            var map = new google.maps.Map(document.getElementById("map"),myOptions);
                            map.setCenter(results[0].geometry.location);
                            var marker = new google.maps.Marker({
                              map: map,
                              position: results[0].geometry.location
                            });
                        }
                        else {
                            alert(":error " + status);
                        }
                    });
                    } else {
                        alert('There was a problem with the request.'+ httpRequest.status.toString());
                    }
                }
            }

            httpRequest.open(method,url);
            httpRequest.send();
        }
    }
</script>

<html>
  <head>
    <title>Geocoding Service</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #floating-panel {
        position: absolute;
        top: 10px;
        left: 25%;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
        text-align: center;
        font-family: 'Roboto','sans-serif';
        line-height: 30px;
        padding-left: 10px;
      }
    </style>
  </head>
  <body>
    <div id="floating-panel">
      <input id="address" type="textbox" value="">
      <input id="submit" type="button" value="Geocode">
    </div>
    <div id="map"></div>
    <script>
    var map
      function initMap() {
          map = new google.maps.Map(document.getElementById('map'), {
          zoom: 8,
          center: {lat: -34.397, lng: 150.644}
        });      
      }

    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIqfSyCbzKZLTVlEJosmQQy_RKSyFczidmpw63M&callback=initMap">
    </script>
  </body>
</html>

 效果如下:

初始界面

查询得到结果并定位

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值