新建FastApi项目
导入需要依赖
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
import requests
from jinja2 import Template
在项目根目录下新建templates文件夹以存储静态文件
在main.py下编写根据IP地址解析用户所在城市
代码语言:txt复制@app.get("/map", response_class=HTMLResponse)
async def root(request: Request):
# 获取用户IP地址
user_ip = "70.247.94.66"
# 使用百度地图API获取用户所在城市
baidu_api_key = "你自己的ak"
baidu_api_url = f"https://****?ak={baidu_api_key}&ip={user_ip}&coor=bd09ll"
response = requests.get(baidu_api_url)
city = response.json()["content"]["address_detail"]["city"]
x = response.json()["content"]["point"]["x"]
y = response.json()["content"]["point"]["y"]
# 生成HTML页面
with open("templates/index.html", "r") as f:
template = Template(f.read())
html = template.render(city=city,x=x,y=y)
# 返回HTML页面
return html
编写前端html
代码语言:txt复制<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="//api.map.baidu.com/api?type=webgl&v=1.0&ak=你自己的ak"></script>
<title>根据经纬度定位</title>
<style>
html, body, #allmap{
width: 100%;
height: 100%;
padding: 0;
margin: 0;
overflow: hidden;
}
#result{
padding: 7px 10px;
position: fixed;
top: 10px;
left: 20px;
width: 450px;
background: #fff;
box-shadow: 0 2px 6px 0 rgba(27, 142, 236, 0.5);
border-radius: 7px;
z-index: 99;
}
#result input{
width:130px;
margin-right:10px;
height:25px;
border: 1px solid rgba(27, 142, 236, 0.5);
border-radius: 5px;
}
#result button{
border: 1px solid rgba(27, 142, 236, 0.5);
border-radius: 5px;
background: rgba(27, 142, 236, 0.5);
color: #fff
}
</style>
</head>
<body>
<div id='allmap'></div>
<div id='result'>
经度: <input id="lng" value="{{x}}" type="text"/>
纬度: <input id="lat" value="{{y}}" type="text"/>
<button onclick="theLocation()"/>查询</button>
</div>
<script>
// 百度地图API功能
var map = new BMapGL.Map("allmap");
map.centerAndZoom(new BMapGL.Point(116.331398,39.897445),11);
map.enableScrollWheelZoom(true);
// 用经纬度设置地图中心点
function theLocation(){
if(document.getElementById("lng").value != "" && document.getElementById("lat").value != ""){
map.clearOverlays();
var new_point = new BMapGL.Point(document.getElementById("lng").value,document.getElementById("lat").value);
var marker = new BMapGL.Marker(new_point); // 创建标注
map.addOverlay(marker); // 将标注添加到地图中
map.panTo(new_point);
}
}
</script>
</body>
</html>
启动项目,请求
代码语言:txt复制http://127.0.0.1:8000/map
点击查询
百度地图有海量api可进行调用,FastApi集成百度地图api调用,完整代码请回复关键字【fastapi】获取