web H5 调用高德地图 通过ip定位获取当前城市
一、使用步骤注册高德账号,创建应该获取key ; 登录之后, 点击“应用”(头部导航栏)
注册地址拿走-------》: https://lbs.amap.com/dev/id/choose
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210125180145205.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MTYxODkxNw==,size_16,color_FFFFFF,t_70)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210125185034565.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MTYxODkxNw==,size_16,color_FFFFFF,t_70)
注意这里有服务类型,提交完成后,复制 该 key
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210125183453791.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MTYxODkxNw==,size_16,color_FFFFFF,t_70)
二、直接上代码
代码如下(示例):
<script type="text/javascript" src="http://webapi.amap.com/maps?v=2.0&key=xxxxx&plugin=AMap.CitySearch"></script>
getCity(){
const map = new AMap.Map('container', {
resizeEnable: true
});
const citysearch = new AMap.CitySearch();
//自动获取用户IP,返回当前城市
citysearch.getLocalCity( (status, result)=> {
if (status === 'complete' && result.info === 'OK') {
if (result && result.city && result.bounds) {
const cityinfo = result.city;
const citybounds = result.bounds;
//地图显示当前城市
// map.setBounds(citybounds);
console.log('当前所在城市', result)
}
} else {
console.log('没有获取到位置时');
}
});
AMap.plugin('AMap.Geolocation', ()=> {
const geolocation = new AMap.Geolocation({
enableHighAccuracy: true,//是否使用高精度定位,默认:true
timeout: 10000, //超过10秒后停止定位,默认:5s
buttonPosition: 'RB', //定位按钮的停靠位置
buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
});
map.addControl(geolocation);
geolocation.getCurrentPosition(function(status,result){
if(status=='complete'){
//解析定位结果
console.log('当前所在城市', result)
}else{
//解析定位错误信息
console.log('解析定位错误信息');
}
})
})
},