Use NodeJS to implement the interface for batch query of geographical locations by longitude and latitude.
Steps
1. query interface
There are still many such types of interfaces on the website. I have directly called Baidu map's interface. The interface documentation calls the Geocoding API's geographic code service.
Request example: Perform geographic code query on Baidu building in Beijing
Http://api.map.baidu.com/geocoder/v2? Ak = e4805d16520de693a3fe707gj962045 & callback = renderOption & output = json & address = Baidu tower & city = Beijing
An ak parameter is required. This parameter is a string generated when you create an application and must be called when you request data.
[Note]
The created application is of the server type.
There are two verification methods for creating an application. You can use the IP address whitelist for verification or the sn for verification, the difference between the two is that the IP address needs to be set in advance when you request an IP address. If you do not want to set a dead IP address in advance, you can also select sn verification, which uses md5 as the encryption algorithm's verification method.
At the beginning, I chose the sn for verification. However, I can only use the ip address whitelist for verification when calling crypto to generate the md5 Signature.
2. query by nodejs
With the interface for calling, we can write a small script to request data. We need three dependencies: express, superagent, and eventproxy.
Express is a lightweight web Application
Superagent is a library frequently used by crawlers and can simulate various requests.
Eventproxy is a concurrency controller.
* Simple query
First, we need to write a simple request to check whether the location can be obtained:
App. get ('/one', function (req, res, next) {var sk = 'yoursk' // sk for creating an application, 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 to 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, it indicates that the interface is successful. If the status is not 0, please refer to the return code status table.
Why do we need to open a server to request it? Because the application we created is a server, we need to create a server to request it.
* Batch query
Now, a city can be queried. Next we will query multiple cities. We use eventproxy for concurrency control. You can regard it as a counter, you can run the command to listen to an event and execute the corresponding function after n times.
The key code is as follows:
App. get ('/taobao', function (req, res, next) {var sk = 'yoursk', addresses = ['beijing', 'shenzhen', 'guangzhou ', 'punning']; 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 a browser to access:http://localhost:8888/many
[{Address: "Beijing", res: "{" status ": 0," result ": {" location ": {" lng ": 116.39564503787867," lat ": 39.92998577808024}, "precise": 0, "confidence": 10, "level": "city" }}, {address: "Shenzhen City", res: "{" status ": 0," result ": {" location ": {" lng ": 114.0259736573215," lat ": 22.546053546205248}," precise ": 0, "confidence": 14, "level": "city" }}" },{ address: "Guangzhou City", res: "{" status ": 0," result ": {"location": {"lng": 113.30764967515182, "lat": 23.12004910207623}, "precise": 0, "confidence": 12, "level ": "city" }}, {address: "Puning City", res: "{" status ": 0," result ": {" location ": {" lng ": 116.07816590835329, "lat": 23.28895358314155}, "precise": 0, "confidence": 14, "level": "district/county"}]
Okay, there is no problem with batch query. Next we will use nodejs to read the excel file that the background engineer threw to me.
3. nodejs reads and writes files.
This time we need two more dependencies, one built-in fs module for nodejs and one library for reading and writing excel node-xlsx
Drop the excel file of the city to the root directory, and create another script xls2js. js:
var xlsx = require('node-xlsx') , fs = require('fs') ;var file_path = './query_result.xlsx';var file_data = xlsx.parse(file_path);
Call fs. writeFile to write the extracted city. 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 row is generally the header, but not necessarily, sheetbody = sheetdata. slice (1) // real data, file_path_towrite = '. /static/address. json ', file_data_json, cities_name = []; // write the city 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 ('data writing failed', err); else console. log ('file written successfully ');})})
Open the static/address. json file and you will see the text in the following format:
{"Cities_name": ["Beijing, Beijing", "Beijing, city jurisdiction", "Tianjin, Tianjin"]}
4. Comprehensive steps 2 and 3 implement an interface for reading local city files, querying files in batches, and writing new files
Now, with this file, we can read it again and perform 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 ('file reading 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. log ('data writing failed', err); else console. log ('data retrieved and written to the file'); res. send (file_data) ;})}) addresses. forEach (function (e, I) {superagent. get ('HTTP: // api.map.baidu.com/geocoder/v2 /'). query ({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. Implement a Web page that can input geographical locations for batch query of geographical locations
These are the front-end things. How can they be nice?
6. Summary
The above is all the content of the interface for batch query of geographical longitude and latitude using NodeJS. I hope it will be helpful for you to use nodejs.