场景:首页显示当前城市及其气温
采用百度地图api
ak 是在百度地图开发者平台申请的密钥 详见 http://lbsyun.baidu.com/apiconsole/key
<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=x5q3GuwjwCwkgcofT6TShe0jHWcTmg8c"></script>
<script>
var geolocation = new BMap.Geolocation()
geolocation.getCurrentPosition(function(res){
if (window.location.pathname === '/') {
var lat = res.latitude // 纬度
var lng = res.longitude // 经度
fetch('http://data.cma.cn/kbweb/home/live', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({ "lat": lat,
"lon": lng,
"type": "0" }),
}).then(response => response.json())
.then(data0 => {
var ds = data0.result.DS[0];
var tem = ds.TEM;
if (tem == '9999') {
tem = '--';
}
var portalData = {
province: res.address.province, // 当前省
city: res.address.city, // 当前市
weather: tem + '°C' // 当前城市气温
}
sessionStorage.setItem('portalData',JSON.stringify(portalData))
})
.catch(err => console.log('Request Failed', err))
}
})