如何通过用户IP获取经纬度并在Python Folium地图中标记位置
IP地址转经纬度实现方案
你可以通过IP地理位置查询能力将拿到的client_ip转换为经纬度,以下是两种可直接落地的实现方式:
方案1:离线IP库实现(无外部请求、响应速度快)
推荐使用开源离线IP库实现,不需要调用外部服务,适配内网部署场景:
- 第一步安装Python依赖包:
pip install ip2region - 第二步获取官方公开的免费IP数据文件(xdb格式),放到Django项目的可访问目录下
- 第三步集成到现有业务代码中:
from ipware import get_client_ip from ip2region import Searcher import folium # 初始化IP查询对象,替换为你项目中xdb文件的实际路径 db_path = "./ip2region.xdb" searcher = Searcher.new_with_file_buffer(db_path) # 预维护城市与经纬度的映射表,可按需补充更多城市 city_coords = { "北京": (39.9042, 116.4074), "上海": (31.2304, 121.4737), "广州": (23.1291, 113.2644), "深圳": (22.5431, 114.0579) } def getlocation(request): client_ip, is_routable = get_client_ip(request) # 设置默认经纬度,查询失败时兜底使用 latitude, longitude = 39.9042, 116.4074 if client_ip and is_routable: try: # 查询IP对应的行政区划信息 region_info = searcher.search(client_ip) # 返回格式为:国家|区域|省份|城市|ISP,提取城市字段匹配映射表 city = region_info.split('|')[3] if city in city_coords: latitude, longitude = city_coords[city] except Exception: # 查询异常时不中断逻辑,继续使用默认坐标 pass # 原有Folium地图绘制逻辑 map1 = folium.Map(location=[latitude,longitude], zoom_start=12, control_scale=True,prefer_canvas=True) folium.CircleMarker(location = [latitude,longitude],radius = 20, popup= 'Here You Are',fill=True,fill_color="#3186cc",).add_to(map1) folium.Marker([latitude,longitude], popup ='Your Location').add_to(map1) # 后续返回地图渲染结果即可
方案2:公共IP查询接口实现(无需维护本地数据、精度更高)
如果你的服务可以访问公网,也可以调用公共IP查询接口直接获取经纬度:
- 第一步安装网络请求依赖:
pip install requests - 第二步集成到代码中:
from ipware import get_client_ip import requests import folium def getlocation(request): client_ip, is_routable = get_client_ip(request) latitude, longitude = 39.9042, 116.4074 if client_ip and is_routable: try: # 替换为你选用的IP查询接口地址,按接口要求传入IP参数即可 resp = requests.get(f"自定义接口地址?ip={client_ip}", timeout=2) resp_data = resp.json() # 按接口返回的字段解析经纬度,通常字段为lat/lon或latitude/longitude latitude = resp_data.get("latitude", latitude) longitude = resp_data.get("longitude", longitude) except Exception: # 请求或解析失败时使用默认坐标 pass # 原有Folium地图绘制逻辑 map1 = folium.Map(location=[latitude,longitude], zoom_start=12, control_scale=True,prefer_canvas=True) folium.CircleMarker(location = [latitude,longitude],radius = 20, popup= 'Here You Are',fill=True,fill_color="#3186cc",).add_to(map1) folium.Marker([latitude,longitude], popup ='Your Location').add_to(map1)
注意事项
- 局域网IP、本地回环IP(127.0.0.1)无法查询公网地理位置,这类场景直接使用默认坐标即可
- IP定位的精度有限,若需要更高精度的位置信息,建议在前端调用系统定位API获取用户授权后的实时经纬度
内容的提问来源于stack exchange,提问作者Md Fahad Hossain
相关产品推荐
相关产品推荐

