Using Nodejs to realize the geographical latitude and longitude interface _node.js

Source: Internet
Author: User
Tags emit md5

Implementation steps

1. Query interface

This type of interface on the website is still quite a lot, the author directly find the interface of Baidu map to do, interface documents, calling API is the Geocoding API in the geographical coding services

Request example: The Beijing Baidu Mansion carries on the geographical Code inquiry

http://api.map.baidu.com/geocoder/v2/?ak=E4805d16520de693a3fe707cdc962045&callback=renderOption&output=json&address=百度大厦&city=北京市

This requires an AK parameter, which is a string of strings generated when the user creates the application, and needs to be invoked when the data is requested.

Attention

The application created is a service-side type

There are two ways to create applications to choose from, you can choose to use the IP whitelist checksum, you can choose to use the SN to do the check, the difference is that the IP need to set up in advance when you request the IP address, if you do not want to set the dead IP address in advance, you can also choose This is the use of MD5 as a verification method of encryption algorithm.
The author first chooses SN to do the checksum, but calls the crypto generation MD5 signature has been verified however, only use the IP whitelist as a checksum

2, Nodejs for inquiries

With the interface for the call, we can write a small script to request the data, we need three dependencies, respectively, Express, Superagent, Eventproxy
Express is a lightweight web application

Superagent is a common repository for reptiles that can simulate various requests

Eventproxy is a concurrent controller

* Simple Query

First, let's write a simple request to check to see if we can get a location:

 App.get ('/one ', function (req, res, next) {
  
  var sk = ' Yoursk '//Create application SK
    , address = ' Beijing '
    ;
  Superagent.get (' http://api.map.baidu.com/geocoder/v2/')
    . Query ({address:address})
    . Query ({output: ' JSON '})
    . Query ({Ak:sk}). End
    (function (err, sres) {
      if (err) {
        console.log (' err: ', err);
        return;
      }
      Res.send (Sres.text);
    }) 
 

Then open the browser access:http://localhost:8888/one

{
  status:0, result
  : {
  location: {
    lng:116.39564503787867,
    lat:39.92998577808024
  },
  precise:0,
  confidence:10, Level
  : "City"
}

When you can see this information, the interface is successful, if the status is not 0, please refer to the Return Code status table

Why do we have to open a special server to request it, because we create the application is the server, we need to build a servers to request.

* Bulk Query

Well, a city can be queried, and then we have to do a number of city queries, we use Eventproxy to do concurrency control, you can think of it as a counter, you can command it to listen to an event, and after N times to perform the corresponding function.

The key code is as follows:

App.get ('/many ', function (req, res, next) {
  var sk = ' Yoursk '
    , addresses = [' Beijing ', ' Shenzhen ', ' Guangzhou ', ' Puning ']
    ; 
   
    ep.after (' getLocation ', addresses.length, function (locations) {
    res.send (locations);
  })
  Addresses.foreach (function (e, i) {
    superagent.get (' http://api.map.baidu.com/geocoder/v2/')
      . Query ({ Address:e})
      . Query ({output: ' JSON '}).
      query ({ak:sk}). End
      (function (err, sres) {
        ep.emit (' GetLocation ', {address:e, res:sres.text})})})

   

Open Browser access:http://localhost:8888/many

[
{address
: "Beijing,
Res:" {"status": 0, "result": {"location": {"LNG": 116.39564503787867, "lat" : 39.92998577808024}, "precise": 0, "confidence": ten, "Level": "City"}} "
},
{address
:" Shenzhen ",
Res:" {" Status ": 0," result ": {" location ": {" LNG ": 114.0259736573215," lat ": 22.546053546205248}," precise ": 0," confidence ": 14, ' Level ': ' City '} '}
,
{address
: ' Guangzhou ',
res: ' {' status ': 0, ' result ': {' location ': {' LNG ' : 113.30764967515182, "lat": 23.12004910207623}, "precise": 0, "confidence": A, "Level": "City"} "
},
{
Address: "Puning",
res: "{status]: 0," result ": {" location ": {" LNG ": 116.07816590835329," lat ": 23.28895358314155}," Precise ": 0," confidence ":" Level ":" County "}"
}
]

OK, the bulk query is no problem, next we have to use Nodejs to read the backend engineer to throw me the Excel file

3, Nodejs read and write files

This time we need two more dependencies, a Nodejs built-in FS module, a library for reading and writing Excel node-xlsx

The Excel file for the city will be dropped into the root directory, and a script xls2js.js:

var xlsx = require (' node-xlsx ')
  , fs = require (' FS ')
  ;
var file_path = './query_result.xlsx ';
var file_data = Xlsx.parse (File_path);

Then call Fs.writefile will be extracted from the city to write, the code is as follows:

File_data.foreach (function (sheet, index) {
  var sheetname = sheet.name//table name
    , Sheetdata = sheet.data//table Data 
   , Sheethead = sheetdata[0]//The first line is generally header, but not certain
    , sheetbody = Sheetdata.slice (1)//Real data
    , File_path_towrite = ' ./static/address.json '
    , File_data_json
    , cities_name = []
    ;
  Write the city's data into the
  Sheetbody.foreach (function (e, i) {
    Cities_name.push (' + e[1] + ', ' + e[2 ')
  })
  File_ Data_json = Json.stringify ({cities_name:cities_name});
  Fs.writefile (file_path_towrite, File_data_json, function (err) {
    if (err) 
      console.log (' Write data failed ', err);
    else 
      console.log (' Write file succeeded ');
  })

Open the Static/address.json file and you will see text in the following format:

{"Cities_name": ["Beijing, Beijing", "Beijing, Municipal District", "Tianjin, Tianjin"]}

4, integrated steps 2, 3 to achieve a read local city files, batch query, write new file interface

Well, with this file, we can read it again and do a batch query:

App.get ('/', function (req, res, next) {var sk = ' Yoursk ', addresses = [], File_path = './static/address.json

  ', File_path_towrite = './static/geocoder.json ', file_data;
      Fs.readfile (File_path, function (err, data) {if (err) {console.log (' Read file failed ', err);
    Return
    } File_data = Json.parse (data);
    
    addresses = File_data.cities_name;
      Ep.after (' getLocation ', addresses.length, function (locations) {var file_data = {}; Locations.foreach (function (e, i) {file_data[e.address.split (', ') [1]] = [e[' location '] [' LNG '], e[' location '] [' lat ']
      ]]; }) Fs.writefile (File_path_towrite, Json.stringify (File_data), function (err) {if (err) Console.lo
        G (' Write data failed ', err);
        else Console.log (' Get data and write file successfully ');
      Res.send (File_data); }) Addresses.foreach (function (e, i) {superagent.get (' http://api.map.baidu.com/geocoder/v2/'). Qu Ery ({address:e.split (', ').Join (')}). Query ({city:e.split (', ') [1]}). query ({output: ' JSON '}). Query ({Ak:sk}). End
          (Function (err, sres) {var location, Res_json;
          Res_json = Json.parse (Sres.text); if (Res_json.status = = 0) {location = Res_json.result && Res_json.result.location | |
          '';
          else {location = {"LNG": 0, "lat": 0};
} ep.emit (' GetLocation ', {address:e, location:location})})}); })

5, the implementation of a Web page, you can enter the geographical location of the bulk query

This is the front of the thing, how to look good how to write

6, summary

The above is to use NODEJS to achieve the bulk of the geographical latitude and longitude of the interface of the entire content, I hope to use Nodejs can help.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.