我注意到,从谷歌地图页面,你可以得到一个"嵌入"链接,把一个iframe和加载地图在浏览器中。(这里没有新闻)
图像大小可以调整为非常大,所以我有兴趣获得一些大图像作为单个。png。
更具体地说,我想从一个边界框(右上角和左下角的坐标)定义一个矩形区域,并获得相应的图像,具有适当的缩放系数。
但我的问题是:我如何使用Python来获得这个地图的"像素内容"作为一个图像对象?
(我的理由是:如果浏览器可以获取和呈现这样的图像内容,那么Python也应该能够做到这一点)。
编辑:这是显示我的示例地图的HTML文件的内容:<iframe
width="2000"
height="1500"
frameborder="0"
scrolling="yes"
marginheight="0"
marginwidth="0"
src="http://maps.google.com.br/maps?hl=pt-BR&ll=-30.027489,-51.229248&spn=1.783415,2.745209&z=10&output=embed"/>
编辑:我按照Ned Batchelder的建议,使用上述iframe中的src
地址读取urllib.urlopen()
调用的内容。结果是大量的javascript代码,我认为这与Google Maps javascript API有关。那么,问题来了:我怎样才能在Python中利用这些东西做一些有用的事情来获得地图图像?
编辑:这个链接似乎包含了一些非常相关的信息,关于谷歌地图如何贴片他们的地图:http://www.codeproject.com/KB/scrapbook/googlemap.aspx
也:http://econym.org.uk/gmap/howitworks.htm
谢谢大家的回答。我最终以另一种方式解决了这个问题,使用Google Maps静态API和一些公式将坐标空间转换为像素空间,这样我就可以得到精确的图像,这些图像可以很好地"缝合"在一起。
对于任何感兴趣的人,这里是代码。如果有帮助,请评论!
=============================
import Image, urllib, StringIO
from math import log, exp, tan, atan, pi, ceil
EARTH_RADIUS = 6378137
EQUATOR_CIRCUMFERENCE = 2 * pi * EARTH_RADIUS
INITIAL_RESOLUTION = EQUATOR_CIRCUMFERENCE / 256.0
ORIGIN_SHIFT = EQUATOR_CIRCUMFERENCE / 2.0
def latlontopixels(lat, lon, zoom):
mx = (lon * ORIGIN_SHIFT) / 180.0
my = log(tan((90 + lat) * pi/360.0))/(pi/180.0)
my = (my * ORIGIN_SHIFT) /180.0
res = INITIAL_RESOLUTION / (2**zoom)
px = (mx + ORIGIN_SHIFT) / res
py = (my + ORIGIN_SHIFT) / res
return px, py
def pixelstolatlon(px, py, zoom):
res = INITIAL_RESOLUTION / (2**zoom)
mx = px * res - ORIGIN_SHIFT
my = py * res - ORIGIN_SHIFT
lat = (my / ORIGIN_SHIFT) * 180.0
lat = 180 / pi * (2*atan(exp(lat*pi/180.0)) - pi/2.0)
lon = (mx / ORIGIN_SHIFT) * 180.0
return lat, lon
############################################
# a neighbourhood in Lajeado, Brazil:
upperleft = '-29.44,-52.0'
lowerright = '-29.45,-51.98'
zoom = 18 # be careful not to get too many images!
############################################
ullat, ullon = map(float, upperleft.split(','))
lrlat, lrlon = map(float, lowerright.split(','))
# Set some important parameters
scale = 1
maxsize = 640
# convert all these coordinates to pixels
ulx, uly = latlontopixels(ullat, ullon, zoom)
lrx, lry = latlontopixels(lrlat, lrlon, zoom)
# calculate total pixel dimensions of final image
dx, dy = lrx - ulx, uly - lry
# calculate rows and columns
cols, rows = int(ceil(dx/maxsize)), int(ceil(dy/maxsize))
# calculate pixel dimensions of each small image
bottom = 120
largura = int(ceil(dx/cols))
altura = int(ceil(dy/rows))
alturaplus = altura + bottom
final = Image.new("RGB", (int(dx), int(dy)))
for x in range(cols):
for y in range(rows):
dxn = largura * (0.5 + x)
dyn = altura * (0.5 + y)
latn, lonn = pixelstolatlon(ulx + dxn, uly - dyn - bottom/2, zoom)
position = ','.join((str(latn), str(lonn)))
print x, y, position
urlparams = urllib.urlencode({'center': position,
'zoom': str(zoom),
'size': '%dx%d' % (largura, alturaplus),
'maptype': 'satellite',
'sensor': 'false',
'scale': scale})
url = 'http://maps.google.com/maps/api/staticmap?' + urlparams
f=urllib.urlopen(url)
im=Image.open(StringIO.StringIO(f.read()))
final.paste(im, (int(x*largura), int(y*altura)))
final.show()
与其尝试使用嵌入链接,不如直接到Google API获取静态图形的图像。这是Google Maps静态图像API的链接——看起来你可以在URL中传入long/lat参数,就像你在普通的可嵌入的URL中所做的那样。例如:
http://maps.googleapis.com/maps/api/staticmap?center=-30.027489,-51.229248&size=600x600&zoom=14&sensor=false
以你上面给出的坐标为中心,给出600x600的街道概览,这似乎是巴西的阿雷格里港。现在你可以按照Ned的建议使用urlopen
和PIL
:
from cStringIO import StringIO
import Image
import urllib
url = "http://maps.googleapis.com/maps/api/staticmap?center=-30.027489,-51.229248&size=800x800&zoom=14&sensor=false"
buffer = StringIO(urllib.urlopen(url).read())
image = Image.open(buffer)
编辑:这个答案中的代码已经改进和简化,在这里:https://stackoverflow.com/a/50536888/5859283
根据heltonbiker的精彩回答和BenElgar的更改,以下是Python 3的一些更新代码和API键访问的添加,希望对某些人有用:
"""
Stitch together Google Maps images from lat, long coordinates
Based on work by heltonbiker and BenElgar
Changes:
* updated for Python 3
* added Google Cloud Static Maps API key field (now required for access)
* handle http request exceptions
"""
import requests
from io import BytesIO
from math import log, exp, tan, atan, pi, ceil
from PIL import Image
import sys
EARTH_RADIUS = 6378137
EQUATOR_CIRCUMFERENCE = 2 * pi * EARTH_RADIUS
INITIAL_RESOLUTION = EQUATOR_CIRCUMFERENCE / 256.0
ORIGIN_SHIFT = EQUATOR_CIRCUMFERENCE / 2.0
GOOGLE_MAPS_API_KEY = 'change this to your API key'
def latlontopixels(lat, lon, zoom):
mx = (lon * ORIGIN_SHIFT) / 180.0
my = log(tan((90 + lat) * pi/360.0))/(pi/180.0)
my = (my * ORIGIN_SHIFT) /180.0
res = INITIAL_RESOLUTION / (2**zoom)
px = (mx + ORIGIN_SHIFT) / res
py = (my + ORIGIN_SHIFT) / res
return px, py
def pixelstolatlon(px, py, zoom):
res = INITIAL_RESOLUTION / (2**zoom)
mx = px * res - ORIGIN_SHIFT
my = py * res - ORIGIN_SHIFT
lat = (my / ORIGIN_SHIFT) * 180.0
lat = 180 / pi * (2*atan(exp(lat*pi/180.0)) - pi/2.0)
lon = (mx / ORIGIN_SHIFT) * 180.0
return lat, lon
def get_maps_image(NW_lat_long, SE_lat_long, zoom=18):
ullat, ullon = NW_lat_long
lrlat, lrlon = SE_lat_long
# Set some important parameters
scale = 1
maxsize = 640
# convert all these coordinates to pixels
ulx, uly = latlontopixels(ullat, ullon, zoom)
lrx, lry = latlontopixels(lrlat, lrlon, zoom)
# calculate total pixel dimensions of final image
dx, dy = lrx - ulx, uly - lry
# calculate rows and columns
cols, rows = int(ceil(dx/maxsize)), int(ceil(dy/maxsize))
# calculate pixel dimensions of each small image
bottom = 120
largura = int(ceil(dx/cols))
altura = int(ceil(dy/rows))
alturaplus = altura + bottom
# assemble the image from stitched
final = Image.new("RGB", (int(dx), int(dy)))
for x in range(cols):
for y in range(rows):
dxn = largura * (0.5 + x)
dyn = altura * (0.5 + y)
latn, lonn = pixelstolatlon(ulx + dxn, uly - dyn - bottom/2, zoom)
position = ','.join((str(latn), str(lonn)))
print(x, y, position)
urlparams = {'center': position,
'zoom': str(zoom),
'size': '%dx%d' % (largura, alturaplus),
'maptype': 'satellite',
'sensor': 'false',
'scale': scale}
if GOOGLE_MAPS_API_KEY is not None:
urlparams['key'] = GOOGLE_MAPS_API_KEY
url = 'http://maps.google.com/maps/api/staticmap'
try:
response = requests.get(url, params=urlparams)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(e)
sys.exit(1)
im = Image.open(BytesIO(response.content))
final.paste(im, (int(x*largura), int(y*altura)))
return final
############################################
if __name__ == '__main__':
# a neighbourhood in Lajeado, Brazil:
NW_lat_long = (-29.44,-52.0)
SE_lat_long = (-29.45,-51.98)
zoom = 18 # be careful not to get too many images!
result = get_maps_image(NW_lat_long, SE_lat_long, zoom=18)
result.show()
@4Oh4的答案是正确的,但数学比他们需要的更复杂。度和弧度之间的转换发生得比他们需要的更频繁。地球的半径没有任何理由——它在所有的计算中都被取消了。在像素坐标中无故添加偏移量。标志的截断比它需要的要大。还有一些其他的零碎的东西,已经写在改动里了。这是我的版本:
#!/usr/bin/env python
"""
Stitch together Google Maps images from lat, long coordinates
Based on work by heltonbiker and BenElgar
Changes:
* updated for Python 3
* added Google Maps API key (compliance with T&C, although can set to None)
* handle http request exceptions
With contributions from Eric Toombs.
Changes:
* Dramatically simplified the maths.
* Set a more reasonable default logo cutoff.
* Added global constants for logo cutoff and max image size.
* Translated a couple presumably Portuguese variable names to English.
"""
import requests
from io import BytesIO
from math import log, exp, tan, atan, ceil
from PIL import Image
import sys
# circumference/radius
tau = 6.283185307179586
# One degree in radians, i.e. in the units the machine uses to store angle,
# which is always radians. For converting to and from degrees. See code for
# usage demonstration.
DEGREE = tau/360
ZOOM_OFFSET = 8
GOOGLE_MAPS_API_KEY = None # set to 'your_API_key'
# Max width or height of a single image grabbed from Google.
MAXSIZE = 640
# For cutting off the logos at the bottom of each of the grabbed images. The
# logo height in pixels is assumed to be less than this amount.
LOGO_CUTOFF = 32
def latlon2pixels(lat, lon, zoom):
mx = lon
my = log(tan((lat + tau/4)/2))
res = 2**(zoom + ZOOM_OFFSET) / tau
px = mx*res
py = my*res
return px, py
def pixels2latlon(px, py, zoom):
res = 2**(zoom + ZOOM_OFFSET) / tau
mx = px/res
my = py/res
lon = mx
lat = 2*atan(exp(my)) - tau/4
return lat, lon
def get_maps_image(NW_lat_long, SE_lat_long, zoom=18):
ullat, ullon = NW_lat_long
lrlat, lrlon = SE_lat_long
# convert all these coordinates to pixels
ulx, uly = latlon2pixels(ullat, ullon, zoom)
lrx, lry = latlon2pixels(lrlat, lrlon, zoom)
# calculate total pixel dimensions of final image
dx, dy = lrx - ulx, uly - lry
# calculate rows and columns
cols, rows = ceil(dx/MAXSIZE), ceil(dy/MAXSIZE)
# calculate pixel dimensions of each small image
width = ceil(dx/cols)
height = ceil(dy/rows)
heightplus = height + LOGO_CUTOFF
# assemble the image from stitched
final = Image.new('RGB', (int(dx), int(dy)))
for x in range(cols):
for y in range(rows):
dxn = width * (0.5 + x)
dyn = height * (0.5 + y)
latn, lonn = pixels2latlon(
ulx + dxn, uly - dyn - LOGO_CUTOFF/2, zoom)
position = ','.join((str(latn/DEGREE), str(lonn/DEGREE)))
print(x, y, position)
urlparams = {
'center': position,
'zoom': str(zoom),
'size': '%dx%d' % (width, heightplus),
'maptype': 'satellite',
'sensor': 'false',
'scale': 1
}
if GOOGLE_MAPS_API_KEY is not None:
urlparams['key'] = GOOGLE_MAPS_API_KEY
url = 'http://maps.google.com/maps/api/staticmap'
try:
response = requests.get(url, params=urlparams)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(e)
sys.exit(1)
im = Image.open(BytesIO(response.content))
final.paste(im, (int(x*width), int(y*height)))
return final
############################################
if __name__ == '__main__':
# a neighbourhood in Lajeado, Brazil:
NW_lat_long = (-29.44*DEGREE, -52.0*DEGREE)
SE_lat_long = (-29.45*DEGREE, -51.98*DEGREE)
result = get_maps_image(
NW_lat_long,
SE_lat_long,
zoom=18 # be careful not to get too many images!
)
result.show()
这是Daniel Roseman对使用python 3.x的人的回答:
- 假设你已经有了谷歌地图静态图像API
Python 3。x代码:
from io import BytesIO
from PIL import Image
from urllib import request
import matplotlib.pyplot as plt # this is if you want to plot the map using pyplot
url = "http://maps.googleapis.com/maps/api/staticmap?center=-30.027489,-51.229248&size=800x800&zoom=14&sensor=false"
buffer = BytesIO(request.urlopen(url).read())
image = Image.open(buffer)
# Show Using PIL
image.show()
# Or using pyplot
plt.imshow(image)
plt.show()
更简洁的Python 2。X兼容的方法是
from io import BytesIO
import Image
import urllib
url = "http://maps.googleapis.com/maps/api/staticmap?center=52.50058,13.31316&size=800x800&zoom=14"
buffer = BytesIO(urllib.urlopen(url).read())
image = Image.open(buffer)
image.save("map.png")
获取/保存Google静态地图图像(png格式)的最简单方法:
import requests
img = open('tmp.png','wb')
img.write(requests.get('https://maps.googleapis.com/maps/api/staticmap?center=33.0456,131.3009&zoom=12&size=320x385&key=YOUR_API_KEY').content)
img.close()
urllib.urlopen
将打开一个URL,结果将有一个.read()
方法,您可以使用它来获取图像字节。cStringIO
在内存中有一个基于字符串的类文件对象。PIL有一个Image.open
函数,它打开一个类似文件的东西,为您提供一个图像对象。可以询问图像对象的像素值