天地图瓦片之中国区域下载

天地图影像底图之墨卡托投影下载


提示:仅适合墨卡托,你可以先看效果


前言

要求在电脑离线状态下使用天地图,那么你就不得不下载天地图的瓦片数据了。


一、下载需要

  1. 天地图Token(提示:个人和企业区别很大)
  2. IDEA工具

二、下载步骤

1.直接完整代码,里面有注释

代码如下(示例):

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

/**
 * 天地图瓦片下载
 *
 * @date 2023.3.10
 */
public class TianDiTuDownload {
    //影像 - 墨卡托
    public static String img_w = "http://{server}.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk={tk}";

    public static String[] servers = {"t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"};

    public static void main(String[] args) {
        String basePath = "D:/tianditu";
		//注意天地图API访问次数限制
        String tk = "98ae942bdcf11b93668******e48affb6";


        String[] urlArr = {img_w};//要下载的图层
        int minZoom = 1;  //下载开始层级
        int maxZoom = 9;  //下载结束层级
		//坐标祖国
        double startLat = 53.58;//开始纬度(从北到南)
        double endLat = 2.7;//结束纬度(从北到南)
        double startLon = 73.2;//开始经度(从西到东)
        double endLon = 135.15;//结束经度(从西到东)

        ExecutorService exe = Executors.newFixedThreadPool(6);
        //等经纬度第一层是1x2,纬度数量是2^0,经度数量是2^1
        //墨卡托投影第一层是2x2,纬度数量是2^1,经度数量是2^1
        for (int i = 0; i < urlArr.length; i++) {
            String url = urlArr[i].replace("{tk}", tk);
            System.out.println(url);
            String layerName = url.split("tianditu.gov.cn/")[1].split("/wmts?")[0];
                for (int z = minZoom; z <= maxZoom; z++) {
                    double deg = 360.0 / Math.pow(2, z) / 256;//一个像素点代表多少度
                    int startX = (int) ((startLon + 180) / deg / 256);
                    int endX = (int) ((endLon + 180) / deg / 256);
                    int startY = (((int) Math.pow(2, z) * 256 / 2) - (int) ((Math.log(Math.tan((90 + startLat) * Math.PI / 360)) / (Math.PI / 180)) / (360 / Math.pow(2, z) / 256) + 0.5)) / 256;
                    int endY = (((int) Math.pow(2, z) * 256 / 2) - (int) ((Math.log(Math.tan((90 + endLat) * Math.PI / 360)) / (Math.PI / 180)) / (360 / Math.pow(2, z) / 256) + 0.5)) / 256;
                    for (int x = startX; x <= endX; x++) {
                        for (int y = startY; y <= endY; y++) {
                            final String newUrl = url.replace("{server}", servers[(int) (Math.random() * servers.length)]).replace("{z}", z + "").replace("{x}", x + "").replace("{y}", y + "");
                            //System.out.println(newUrl);
                            final String filePath = basePath + "/" + layerName + "/" + z + "/" + x + "/" + y + ".png";
                            exe.execute(new Runnable() {
                                @Override
                                public void run() {
                                    File file = new File(filePath);
                                    if (!file.exists()) {
                                        if (!file.getParentFile().exists()) {
                                            file.getParentFile().mkdirs();
                                        }
                                        boolean loop = true;
                                        int count = 0;
                                        while (loop && count < 5) {//下载出错进行重试,最多5次
                                            count++;
                                            try {
                                                InputStream in = getFileInputStream(newUrl);
                                                OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
                                                byte[] b = new byte[8192];
                                                int len = 0;
                                                while ((len = in.read(b)) > -1) {
                                                    out.write(b, 0, len);
                                                    out.flush();
                                                }
                                                out.close();
                                                in.close();
                                                loop = false;
                                            } catch (Exception e) {
                                                loop = true;
                                            }
                                        }
                                        if (loop) {
                                            System.out.println("下载失败:" + newUrl);
                                        }
                                    }
                                }
                            });
                        }
                    }
                }
            }
        }
        exe.shutdown();
        while (true) {
            try {
                Thread.sleep(1000L);//主线程休眠1秒,等待线程池运行结束,同时避免一直死循环造成CPU浪费
            } catch (InterruptedException e) {
            }
            if (exe.isTerminated()) {//线程池所有线程都结束运行
                break;
            }
        }
    }

    //获取文件下载流
    public static InputStream getFileInputStream(String url) throws Exception {
        InputStream is = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet request = new HttpGet(url);
        request.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        HttpResponse response = httpclient.execute(request);
        response.setHeader("Content-Type", "application/octet-stream");
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        }
        return is;
    }

}

三、效果

(示例)1:层级
这层保存的数据是X,也就是ROW
(示例)2:ROW
这里是你的X,也就是row
(示例)3:COL
这是你的Y,也就是col
(示例)4:最终效果展示

在这里插入图片描述

我这个加了标记,你们应该是没有的

总结

希望可以帮到大家,有错误望指正,共同进步。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猿小路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值