Sky map WMTS map tiles download

        Recently, I encountered such a problem when developing a personal project, that is: local development uses the Tiandi online map service. When deploying it online, it suddenly occurred to me that the open map service provided by Tiandi requires a secret key before it can be used. , and it needs to be connected to the external network, and there is also a limit on the number of accesses. So, how to migrate it in an internal network environment?

        In fact, the solution is very simple: usually during project development, we download remote sensing images/electronic maps/vector data through a third-party map data downloader, then process it and publish it to our own dedicated server. But for individual developers, the first step of data downloading is often the most difficult, because not only must the data reliability, currentness, completeness, etc. be considered, but also whether the coordinate system is correct. If it is incorrect, the coordinate system must be modified. Conversion, image correction processing, etc. are very troublesome.

        However, if you have experience in publishing map services such as WMS/WFS/WMTS, you will immediately understand what a regular map service is. The WMTS service provided by Tiantu is no exception. In fact, it builds an image pyramid, then cuts it layer by layer, and converts it into n pictures of 256*256 for front-end map development.

        Therefore, according to the tile division rules of the sky map (you can study it in depth for more details), at the level level, the corresponding numbers of rows and columns are:

int rowCount = (int) Math.pow(2, level); //行数
int colCount = (int) Math.pow(2, level); //列数

        For friends with limited conditions, you can simply grab the map tiles of the first few levels through network programming and then use them. Of course, it’s just out of interest. Use this article to record daily development. I personally don’t recommend doing this. After all, there is the suspicion of “stealing the fruits of other people’s labor”, that is, free prostitution. In comparison, it is more recommended. The solution is to use Nginx to proxy the map service and cache it locally smoothly. 

        The sample code for downloading level 8 based on Java is as follows. You can adjust the parameters as needed.

package com.example.xwd;


import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class DownloadTIles {

    public static void main(String[] args) {
        String outPath = "D:\\文档资料\\tiles\\";
        downWorld1To3(outPath,8,8);
    }


    //计算瓦片范围-世界范围-[1-TopLevel级]
    private static void downWorld1To3(String basePath, int lowLevel, int TopLevel) {
        System.out.println("basePath=" + basePath);
        for (int level = lowLevel; level <= TopLevel; level++) {
            int rowCount = (int) Math.pow(2, level); //行数
            int colCount = (int) Math.pow(2, level); //列数
            System.out.println("level:" + level + "row:" + rowCount + ",col:" + colCount);
            //下载瓦片
            for (int j = 0; j < colCount; j++) {
                for (int i = 0; i < rowCount; i++) {
                    String url_tilePath = "http://t0.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&tk=您的天地图key=" + i +
                            "&TILECOL=" + j
                            + "&TILEMATRIX=" + level;//拼接请求路径
                    String save_tilePath = level + "/" + j + "/";//拼接存储路径
                    String save_fileName = +i + ".png";//拼接存储名称
                    String fullFolder = basePath + save_tilePath;
                    File folder = new File(fullFolder);
                    System.out.println(folder.getAbsolutePath());
                    if (!folder.exists()) {
                        folder.mkdirs();
                    }
                    File file = new File(folder, save_fileName);
                    System.out.println("存储路径:" + file.getAbsolutePath());
                    downloadTilePNG(url_tilePath, file);
                }
            }
        }

    }


    private static void downloadTilePNG(String tileUrl, File outFile) {
        URL url = null;
        URLConnection urlConnection = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        int len = -1;
        byte[] buffer = new byte[1024];
        try {
            url = new URL(tileUrl);
            urlConnection = url.openConnection();
            urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 SLBrowser/8.0.1.5162 SLBChan/111");
            inputStream = urlConnection.getInputStream();
            outputStream = new FileOutputStream(outFile);
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            System.out.println("success:" + tileUrl);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("error:" + tileUrl);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

       Then get the tile results as shown below, and use Nginx to publish resources,


#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        add_header 'Access-Control-Allow-Origin' '*';
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

    }


}

        Finally, the sample code for local testing using Cesium.js is as follows:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"
    />
    <title>Document</title>
    <link href="../../Build/Cesium/Widgets/widgets.css" rel="stylesheet"/>
    <script src="../../Build/Cesium/Cesium.js"> </script>
    <style>
        *{
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }
        html,body{
            width: 100%;
            height: 100%;
        }
        #map{
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }
    </style>
</head>

<body>
    <div id="map"></div>
    <script>
        Cesium.Ion.defaultAccessToken = "Your AccessToken"
        const viewer = new Cesium.Viewer("map")
        viewer.scene.imageryLayers.removeAll();

        viewer.imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({
            url: "http://localhost:80/tiles/" + '/{z}/{x}/{y}.png',
            minimumLevel: 0,
            maximumLevel: 7
        }));
    </script>
</body>

</html>

 

 

Guess you like

Origin blog.csdn.net/weixin_43524214/article/details/132864103
map
map
Map
Map
Recommended