美文网首页
获取城市id

获取城市id

作者: 简小园 | 来源:发表于2019-06-01 12:33 被阅读0次
获取城市id
html
<button @click="ready">我的位置</button>
<div id="allmap"></div>
js

先定位,再获取定位城市的id
在js里引入import BMap from 'BMap';
引入外部图片import imgIcon from '../assets/img/icon/map_icon.png';

ready(){
  let that=this;
  let geolocation = new BMap.Geolocation();
  geolocation.getCurrentPosition(function(r){
    if(this.getStatus() == BMAP_STATUS_SUCCESS){

      // 创建地图
      let map = new BMap.Map("allmap");
      let point = new BMap.Point(r.point);
      map.centerAndZoom(point,15);
      map.enableScrollWheelZoom(true);//开启滚动

      var mk = new BMap.Marker(r.point);
      let icon = new BMap.Icon(imgIcon,new BMap.Size(20,22));
      map.addOverlay(mk);
      map.panTo(r.point);
      // 获取城市id
      $.ajax({
          url:'http://api.map.baidu.com/geocoder/v2/?ak=134db1b9cf1f1f2b4427210932b34dcb&location=' + r.point.lat + ',' + r.point.lng + '&output=json',
          dataType: 'jsonp',
          success: function(res) {
            alert("当前城市id:"+res.result.cityCode);
          },
          error:function(){alert("没找到城市id");}
      });

      //地图监听事件
      map.addEventListener('click', function (e) {
        map.removeOverlay(mk);
        mk = new BMap.Marker(e.point,{icon:icon});
        map.addOverlay(mk);
        // 点击地图获取城市id
        $.ajax({
            url:'http://api.map.baidu.com/geocoder/v2/?ak=134db1b9cf1f1f2b4427210932b34dcb&location=' + e.point.lat + ',' + e.point.lng + '&output=json',
            dataType: 'jsonp',
            success: function(res) {
              alert("当前点击城市id:"+res.result.cityCode);
            },
            error:function(){alert("没找到城市id");}
        });
      });
    }else {alert('failed'+this.getStatus());}
  });
}
css
button{
    width: 100px;
    height: 30px;
    border: none;
    font-size: 14px;
    font-weight: bold;
    border-radius: 10px;
    background: #769164;
    color: #eee;
    margin: 0 10px;
  }
  button:hover{
    color: #769164;
    background: #eee;
  }
  #allmap{
    width: 800px;
    height: 520px;
    margin: 10px;
  }

相关文章

网友评论

      本文标题:获取城市id

      本文链接:https://www.haomeiwen.com/subject/mlfftctx.html