背景
因为一些特殊的原因,工作环境是和互联网隔离的.然而在工作中又经常遇到一些需要地图可视化的东西.找了一些资料,但是并不很理想.常见的方案就是Folium包…不过内网比较坑,地图加载也比较麻烦.(在外网也一样).于是萌生了一个想法…借助高德地图API(内网也有高德API),结合IPython的IFrame方法来做一些东西.
IPython.display中的IFrame
从一些资料上看到,在IFrame中,可以嵌入网页\PDF\图片等等…嗯,这样的话,我把高德地图的API,写成HTML文件,导入进来不就好了?
入手尝试:
from IPython.display import IFrame
IFrame('map/Map1.html', width="100%", height=450)
效果:
嗯,一次性成功了.接下来,封装成函数不就好了?
自定义函数
引用的高德地图API样例:
https://lbs.amap.com/api/javascript-api/example/geocoder/geocoding
注意点: 必须要填写那个Key,因为一些情况没有Key,是调用不了接口的.
代码:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
<title>地理编码(地址->经纬度)</title>
<link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css"/>
<style>
html,body,#container{
height:100%;
width:100%;
}
.btn{
width:10rem;
margin-left:6.8rem;
}
</style>
</head>
<body>
<div id="container"></div>
<div class="input-card" style='width:28rem;'>
<label style='color:grey'>地理编码,根据地址获取经纬度坐标</label>
<div class="input-item">
<div class="input-item-prepend"><span class="input-item-text" >地址</span></div>
<input id='address' type="text" value='北京市朝阳区阜荣街10号' >
</div>
<div class="input-item">
<div class="input-item-prepend"><span class="input-item-text">经纬度</span></div>
<input id='lnglat' disabled type="text">
</div>
<input id="geo" type="button" class="btn" value="地址 -> 经纬度" />
</div>
<script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=您申请的key值&plugin=AMap.Geocoder"></script>
<script type="text/javascript">
var map = new AMap.Map("container", {
resizeEnable: true
});
var geocoder = new AMap.Geocoder({
city: "010", //城市设为北京,默认:“全国”
});
var marker = new AMap.Marker();
function geoCode() {
var address = document.getElementById('address').value;
geocoder.getLocation(address, function(status, result) {
if (status === 'complete'&&result.geocodes.length) {
var lnglat = result.geocodes[0].location
document.getElementById('lnglat').value = lnglat;
marker.setPosition(lnglat);
map.add(marker);
map.setFitView(marker);
}else{
log.error('根据地址查询位置失败');
}
});
}
document.getElementById("geo").onclick = geoCode;
document.getElementById('address').onkeydown = function(e) {
if (e.keyCode === 13) {
geoCode();
return false;
}
return true;
};
</script>
</body>
</html>
简单的做个Python函数:
def QueryAreaLonLat():
"""
查询特定区域的经纬度信息
"""
return IFrame('map/Map2.html', width="100%", height=450)
嗯…好了.后续有时间了,会慢慢把官方案例转换为有用的函数,方便在一些场景下的开发.