node. JS calls the Geocoding interface of the Baidu Map Web service API to encode the point-bit anti-geo-information

Source: Internet
Author: User

(I moved it from my Sina blog and made some changes.) )

recently hooked up to node. js and JavaScript. Now received a live, to parse a taxi point data geographic information. So I thought of using node. js to invoke the Baidu map API for parsing. The main library used is FS, request.
//Request PackagevarFS = require (' FS ');varRequest = require (' request '));//set the parameters of Baidu APIvarBaiduapikey = "Cqv9u4qhamoojg6rjdotaqsiumxxxxxx";//fill in the application of the AK//open JSON file for point informationvarjsonstring = "";//Create log file write file streamvarWrite = Fs.createwritestream ("20140510_getondropoff_0h-log.txt");//Create read file streamvarsr = Fs.createreadstream (' 20140510_getondropoff_0h.json ', {flags: ' R ', mode:0666}); Sr.on (' Data ',function(chunk) {//listening for read eventsJsonstring + =Chunk;}) Sr.on (' Error ',function(err) {//Listening for error eventsConsole.log (err);}) Sr.on (' End ',function () {    //listen for read completed events    varJsondata =Json.parse (jsonstring); vari = 0; //cycle through each record     for(varListIndexinchjsondata) {        if(Jsondata.hasownproperty (ListIndex)) {varelement =Jsondata[listindex]; varLongitude = element[' Lon ']; varLatitude = element[' Lat ']; //constructs the URL of the Baidu Web Services API            varRooturl = ' http://api.map.baidu.com/geocoder/v2/? ';//root URL            varurl = rooturl + ' Output=json ' + ' &ak= ' + baiduapikey + ' &location= ' + latitude + ', ' + longitude;//Get parameter String            //send a GET requestRequest.get (URL,function(Err, response, body) {i++;//indicates which point the current content is                //parsing Body                Try {                    varResponsejson =Json.parse (body); //Parse Success                    if(responsejson[' status ') = = 0) {                        //If normal parsing data is returnedConsole.log (i + ": success!"); varformatted_address = responsejson[' result ' [' formatted_address '];//Extracting structured addressesjsondata[i-1][' formatted_address '] = ' formatted_address ';//add to the structured address}Else {                        //If you return error resolution dataConsole.log (i + ": fail!" + responsejson[' status ']); Jsondata[i-1][' formatted_address '] = ""; Write.write (i+ ': Request failed! Error code: ' + responsejson[' status ' + ' \ r \ n '); }                } Catch(Error) {//Parse failedjsondata[i-1][' formatted_address '] = ""; Console.log (i+ ": error!" +error.stack); Console.log (body); //output body for referenceWrite.write (i + ":" +error.stack); Write.write ("Body": "+body); }                //If this is the last point, close the file and write the result                if(i = =jsondata.length) {write.end ();                    Write.close (); Fs.writefilesync ("20140510_getondropoff_0h" + "-add" + ". JSON", Json.stringify (Jsondata)); }})}} sr.close ();}); Write.on (' Err ',function(err) {//Listen for the Err event of writeConsole.log (Err.stack);})

Later will fill in the part of the URL, the use of Qs and QueryString have failed, the reason is: Baidu Map API required format is location=latitude,longitude , and if the value of location is written as an array, that is [Latitude,longitude] , QueryString will become Location=latitude&location=longitude , QS can become the following three kinds of forms:

    • Location=latitude&location=longitude
    • Location[0]=latitude&location[1]=longitude
    • Location[]=latitude&location[]=longitude

are not in line with the Baidu Map API interface requirements.

If you want to avoid the trouble of string connection, using the String-format library is also very convenient, but the URL will also knock very long, it is better to use the QueryString library beautiful.

Or you can use the QueryString module in this way.

Querystring.unescape (querystring.stringify ({    "json",    "xxxxxxxxxxxxxxxxxxxxxxxxx"  ,    + "," + Longitude}))

node. JS calls the Geocoding interface of the Baidu Map Web service API to encode the point-bit anti-geo-information

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.