Download baidu map tiles with thread pool

Source: Internet
Author: User
Tags getmessage volatile

Following the previous article, Baidu Map offline function, here mainly on the download tile map specific methods.

1. Use the all-in-all electronic map to download the tile map with watermarks. Where the folder path is tile/level/x/y.jpg, as shown, all-round electronic map 1.9 Download Baidu Map tile is a black spot.

2. Download the image according to the image URL, get httpurlconnection according to the URL, get the input stream InputStream according to the HttpURLConnection, outputstream out with the output stream = new FileOutputStream (file); Write bytes to file. The code is as follows:

/*** Download Image*/ Public classBaidumapdownload {Static volatileInteger c = 0;//Number of successes    Static volatileInteger fail = 0;//Number of failures
Public Static voidMain (string[] args)throwsException {String link= "http://online3.map.bdimg.com/onlinelabel/?qt=tile&x={x}&y={y}&z={z}&styles=pl&udt= 20170712&scaler=1&p=1 "; intz = 19;//level intXmin = 103514;//x Minimum Value intXmax = 104292;//x Maximum Value intYmin = 29400;//y Minimum value intYmax = 30700;//y Maximum value for(inti = xmin; I <= xmax; i++) {//Loop x for(intj = ymin; J <= Ymax; J + +) {//Loop y Try {
URL URL=NewURL (Link.replace ("{x}", I + ""). Replace ("{y}", J + ""). Replace ("{z}", z + "")); HttpURLConnection Conn=(HttpURLConnection) url.openconnection (); Conn.setconnecttimeout (100); Conn.connect (); InputStream in=Conn.getinputstream (); File dir=NewFile ("d:/mybaidumapdownload1/tiles/" + z + "/" +i); if(!dir.exists ()) {Dir.mkdirs (); } File File=NewFile ("d:/mybaidumapdownload1/tiles/" + z + "/" + i + "/" + j + ". jpg"); if(!file.exists ()) {File.createnewfile (); } OutputStream out=Newfileoutputstream (file); byte[] bytes =New byte[1024 * 20]; intLen = 0; while(len = in.read (bytes))! =-1) {out.write (bytes,0, Len); } out.close (); In.close (); //System.out.println ("downloaded successfully:" + z + "_" + i + "_" + j + ". jpg");C++; } Catch(Exception e) {System.out.println (E.getmessage ()); Fail++; }
} //Loop y End}//Loop x EndThread.Sleep (1000); System.out.println ("Total Downloads:" + C + "Zhang"); System.out.println ("Failure:" + fail + "Zhang"); }}

3. The above code can download Baidu pictures, but it is clear that the above code is single-threaded, and will be blocked IO, Baidu map download to the 19th level when there are nearly 1 million tile map. Here is the thread pool Threadpoolexecutor

Optimize the code. It would have been nice to have a two-day plan to cut down the day.

/*** thread pool download picture*/classBdtaskImplementsrunnable{String link; intI//x-coordinate    intJ//y-coordinate    intZ//Zoom Level    Static volatileInteger c = 0;//Number of successes    Static volatileInteger fail = 0;//Number of failures     PublicBdtask (String link,intIintJintz) { This. link =link;  This. i =i;  This. J =J;  This. z =Z; }     Public Static voidMain (string[] args)throwsException {String link= "http://online3.map.bdimg.com/onlinelabel/?qt=tile&x={x}&y={y}&z={z}&styles=pl&udt= 20170712&scaler=1&p=1 "; intz = 12;//level        intXmin = 808;//x Minimum Value        intXmax = 814;//x Maximum Value        intymin = 230;//y Minimum value        intYmax = 239;//y Maximum value //Create thread pool, corepoolsize two threads, max four threads, threads greater than corepoolsize less than maxmumpoolsize wait idle time for 500 milliseconds,        The default value for task queue Linkblockingqueue when not written is the integer default value. Threadpoolexecutor Threadpoolexecutor=NewThreadpoolexecutor (2,4,500, Timeunit.milliseconds,NewLinkedblockingqueue<runnable>());  for(inti = xmin; I <= xmax; i++) {//Loop x             for(intj = ymin; J <= Ymax; J + +) {//Loop yThreadpoolexecutor.execute (NewBdtask (link,i,j,z)); //New Thread (New Bdtask (Link,i,j,z)). Start (); //This method will always create a thread that causes the panic}//Loop y End}//Loop x EndThreadpoolexecutor.shutdown ();//Close the thread pool         while(!threadpoolexecutor.isterminated ()) {}//Keep circulating untilcontinue execution when all tasks are completedSystem.out.println ("Total Download:" + C + "Zhang"); System.out.println ("Failure:" + fail + "Zhang"); }     Public voidrun () {Try{URL URL=NewURL (Link.replace ("{x}", I + ""). Replace ("{y}", J + ""). Replace ("{z}", z + "")); HttpURLConnection Conn=(HttpURLConnection) url.openconnection (); Conn.setconnecttimeout (100);            Conn.connect (); InputStream in=Conn.getinputstream (); File dir=NewFile ("d:/mybaidumapdownload1/tiles/" + z + "/" +i); if(!dir.exists ())            {Dir.mkdirs (); } File File=NewFile ("d:/mybaidumapdownload1/tiles/" + z + "/" + i + "/" + j + ". jpg"); if(!file.exists ())            {File.createnewfile (); } OutputStream out=Newfileoutputstream (file); byte[] bytes =New byte[1024 * 20]; intLen = 0;  while(len = in.read (bytes))! =-1) {out.write (bytes,0, Len);            } out.close ();            In.close (); synchronized(fail) {C++; }        } Catch(Exception e) {System.out.println (E.getmessage ()); synchronized(c) {fail++; }        }    }}

Source

Download baidu map tiles with thread pool

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.