使用python下载地图切片非常方便,只需要知道切片的url规则,就可以将所有地图切片爬取下来。本文使用的python版本为3.6.
谷歌地图卫星影像切片url如下:
http://www.google.cn/maps/vt?lyrs=s@815&gl=cn&x=107&y=49&z=7
我们只需要根据经纬度计算出行列号,带入url中的xy即可,z代表zoom值。代码如下:
1 from urllib import request 2 import re 3 import urllib.request 4 import os 5 import random 6 import math 7 8 agents = [ 9 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36', 10 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.0 Safari/532.5', 11 'Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/532.9 (KHTML, like Gecko) Chrome/5.0.310.0 Safari/532.9', 12 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.514.0 Safari/534.7', 13 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/534.14 (KHTML, like Gecko) Chrome/9.0.601.0 Safari/534.14', 14 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.14 (KHTML, like Gecko) Chrome/10.0.601.0 Safari/534.14', 15 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.20 (KHTML, like Gecko) Chrome/11.0.672.2 Safari/534.20", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.27 (KHTML, like Gecko) Chrome/12.0.712.0 Safari/534.27', 16 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.24 Safari/535.1'] 17 18 19 # 经纬度反算切片行列号 3857坐标系 20 def deg2num(lat_deg, lon_deg, zoom): 21 lat_rad = math.radians(lat_deg) 22 n = 2.0 ** zoom 23 xtile = int((lon_deg + 180.0) / 360.0 * n) 24 ytile = int((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n) 25 return (xtile, ytile) 26 27 28 # 下载图片 29 def getimg(Tpath, Spath, x, y): 30 try: 31 f = open(Spath, 'wb') 32 req = urllib.request.Request(Tpath) 33 req.add_header('User-Agent', random.choice(agents)) # 换用随机的请求头 34 pic = urllib.request.urlopen(req, timeout=60) 35 36 f.write(pic.read()) 37 f.close() 38 print(str(x) + '_' + str(y) + '下载成功') 39 except Exception: 40 print(str(x) + '_' + str(y) + '下载失败,重试') 41 getimg(Tpath, Spath, x, y) 42 43 44 path = r"E:天地图切片" 45 if not os.path.exists(path): 46 os.mkdir(path) 47 48 zoom = 15 # 下载切片的zoom 49 lefttop = deg2num(36.022968, 120.064056, zoom) # 下载切片的左上角角点 50 rightbottom = deg2num(35.894891, 120.344615, zoom) 51 52 print(str(lefttop[0])) 53 print(str(rightbottom[0])) 54 print(str(lefttop[1])) 55 print(str(rightbottom[1])) 56 print("共" + str(lefttop[0] - rightbottom[0])) 57 print("共" + str(lefttop[1] - rightbottom[1])) 58 59 for x in range(lefttop[0], rightbottom[0]): 60 for y in range(lefttop[1], rightbottom[1]): 61 tilepath = "http://t3.tianditu.gov.cn/DataServer?T=cva_w&x=" + str(x) + "&y=" + str(y) + "&l=" + str(zoom) 62 # 天地图的url 可以换成谷歌地图的 63 getimg(tilepath, os.path.join(path, str(x) + "_" + str(y) + ".png"), x, y) 64 print('完成')
如果本文帮到您了,请不吝打赏