Flask中使用Google Maps短链接生成地图窗口定位错误的解决方法
解决Google Maps短链接解析坐标不准确的问题
问题描述
我需要实现一个Flask函数,接收Google Maps短链接并在网页上显示对应位置。现有代码可运行,但提取的经纬度与实际位置不符:例如短链接https://goo.gl/maps/zmU33mYztCEs3G356,代码提取的坐标为(23.613952, 58.459783),但实际精确坐标是(23.614050304553913, 58.46864471825494)。
现有函数代码:
def show_mini_map(map_link): api_key="" # Expand link if 'goo.gl/maps' in map_link: response = requests.get(map_link) map_link = response.url print(map_link) # Extract latitude/longitude match = re.search(r'@([-0-9.]+),([-0-9.]+),', map_link) if match: lat = match.group(1) lon = match.group(2) print(lat) print(lon) else: logging.error(f'Invalid link: {map_link}') return 'Invalid Google Maps link' # URL mini_map_url = f'https://www.google.com/maps/embed/v1/place?key={api_key}&q={lat},{lon}&zoom=15' # HTML html = f'<iframe width="400" height="400" frameborder="0" style="border:0" src="{mini_map_url}" allowfullscreen></iframe>' return html
问题原因
- 短链接跳转后的初始URL中,
@后面的坐标是粗略值;浏览器加载Google Maps页面后会通过JS更新URL,添加包含精确坐标的data参数(格式如!3d纬度!4d经度),但requests只能获取初始跳转URL,无法捕获JS更新后的精确坐标。 - 原正则表达式匹配范围太宽泛,可能误提取到非精确坐标的数值。
解决方案
方案1:优化正则提取精确坐标
优先提取URL中data参数内的精确经纬度,再 fallback 到@后的坐标,这是无需额外API调用的最优方案:
修改后的函数代码:
import requests import re import logging def show_mini_map(map_link): api_key = "YOUR_GOOGLE_MAPS_API_KEY" # 替换为你的Google Maps API密钥 # 展开短链接,确保跟进所有重定向 if 'goo.gl/maps' in map_link: response = requests.get(map_link, allow_redirects=True) map_link = response.url print(map_link) # 优先提取data参数中的精确坐标 match = re.search(r'!3d([-0-9.]+)!4d([-0-9.]+)', map_link) if match: lat = match.group(1) lon = match.group(2) print(f"精确坐标: {lat}, {lon}") else: # fallback到@后的坐标 match = re.search(r'@([-0-9.]+),([-0-9.]+),\d+z', map_link) if match: lat = match.group(1) lon = match.group(2) print(f"备用坐标: {lat}, {lon}") else: logging.error(f'无效链接: {map_link}') return '无效的Google Maps链接' # 生成嵌入地图URL mini_map_url = f'https://www.google.com/maps/embed/v1/place?key={api_key}&q={lat},{lon}&zoom=15' # 生成HTML嵌入代码 html = f'<iframe width="400" height="400" frameborder="0" style="border:0" src="{mini_map_url}" allowfullscreen></iframe>' return html
方案2:使用Google Maps Place API(最可靠)
如果正则提取仍不稳定,建议使用Google Maps Place API直接解析地点,获取100%精确的坐标:
- 前往Google Cloud Console申请API密钥,并启用Places API。
- 从跳转后的URL中提取
place_id,调用API获取精确坐标:
示例代码片段:
# 从跳转后的URL中提取place_id place_id_match = re.search(r'!1s([A-Za-z0-9_-]+)!', map_link) if place_id_match: place_id = place_id_match.group(1) # 调用Place API获取精确坐标 api_url = f'https://maps.googleapis.com/maps/api/place/details/json?place_id={place_id}&key={api_key}' response = requests.get(api_url) place_data = response.json() if place_data['status'] == 'OK': lat = place_data['result']['geometry']['location']['lat'] lon = place_data['result']['geometry']['location']['lng'] print(f"API获取的精确坐标: {lat}, {lon}")
内容的提问来源于stack exchange,提问作者HM T_T
相关产品推荐
相关产品推荐

