问题描述
vue PC项目 使用高德API 获取位置和天气信息
解决方案:
1.在高德地图上申请一个开发者,并且创建一个key 选择web端应用
2.在vue项目中的index.html中 使用script标签 引入生成的key和秘钥
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>你的项目名称</title>
</head>
<body>
<script type="text/javascript">
window._AMapSecurityConfig = {
securityJsCode:'你申请的安全秘钥',
}
</script>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=你申请的key"></script>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
3.在需要获取位置的页面中定义方法 使用citySearch和weather插件
4.可将获取到的天气信息保存至本地缓存再其他页面拉取渲染,注意要JSON.stringify 转化为JSON字符串,拉取的时候再用JSON.parse将JSON字符串转化为对象
getLngLatLocation() {
let that = this;
AMap.plugin("AMap.CitySearch", function () {
var citySearch = new AMap.CitySearch();
citySearch.getLocalCity(function (status, result) {
if (status === "complete" && result.info === "OK") {
// 查询成功,result即为当前所在城市信息
console.log("通过ip获取当前城市:", result);
AMap.plugin("AMap.Weather", function () {
//创建天气查询实例
var weather = new AMap.Weather();
//执行实时天气信息查询
weather.getLive(result.city, function (err, data) {
console.log("天气", data);
if (data) {
that.weather = data.weather;
that.temperature = data.temperature;
that.city = data.city;
let weatherObj = {
weather: data.weather,
temperature: data.temperature,
city: data.city,
};
localStorage.setItem(
"WEATHER_INFO",
JSON.stringify(weatherObj)
);
}else{
console.log(err);
}
});
});
}
});
});
},