0
点赞
收藏
分享

微信扫一扫

vue+高德地图

文章参考:高德地图:概述-地图 JS API v2.0 | 高德地图API (amap.com)

一.引入高德地图

注册高德地图并申请key。public文件夹下index.html中

//public文件夹下index.html中
 <script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key="您申请的key"></script>

二.高德地图使用基础

  • 创建一个容器

<div id="container"></div>

  • 设置容器的的宽度和高度(注:一定要设置容器的宽高)
  • 初始化地图

// 初始化地图
    initMap () {
      var map = new AMap.Map('container', {
        mapStyle: 'amap://styles/normal', //设置地图的显示样式
        zoom: 10, //设置地图的缩放级别
      });
      // 传入经纬度,设置地图中心点
      var position = new AMap.LngLat(116, 39);  // 标准写法
      // 简写 var position = [116, 39]; 
      map.setCenter(position);
      // 获取地图中心点
      var currentCenter = map.getCenter();
    }

  • 完整代码


<template>
  <div id="container"></div>
</template>
 
<script>
import AMapLoader from '@amap/amap-jsapi-loader';
export default {
  data () {
    return {
      //此处不声明 map 对象,可以直接使用 this.map赋值或者采用非响应式的普通对象来存储。
      map: null,
    }
  },
  mounted () {
    this.initMap()
  },
  methods: {
    // 初始化地图
    initMap () {
      var map = new AMap.Map('container', {
        mapStyle: 'amap://styles/normal', //设置地图的显示样式
        zoom: 10, //设置地图的缩放级别
      });
      // 传入经纬度,设置地图中心点
      var position = new AMap.LngLat(116, 39);  // 标准写法
      // 简写 var position = [116, 39]; 
      map.setCenter(position);
      // 获取地图中心点
      var currentCenter = map.getCenter();
    }
  }
}
</script>
 
<style  scoped>
#container {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 200px;
}
</style>

三.高德地图定位

高德地图Api有两种,分别是ip定位和浏览器定位;大部分浏览器已不支持http协议的定位请求,在定位时应采用https协议

  getLocation () {
      var that = this
      //center属性缺省默认定位到用户所在的城市
      var map = new AMap.Map('container', {
        mapStyle: 'amap://styles/normal', //设置地图的显示样式
        zoom: 10, //设置地图的缩放级别
        resizeEnable: true
      });
      AMap.plugin('AMap.Geolocation', function () {
        var geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,//是否使用高精度定位,默认:true
          timeout: 10000,          //超过10秒后停止定位
          buttonPosition: 'RB',    //定位按钮的停靠位置
          buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
          zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition(function (status, result) {
          if (status == 'complete') {
            onComplete(result)
          } else {
            onError(result)
          }
        });
      });
      //解析定位结果
      function onComplete (data) {
        console.log(data.position)
        that.lng = data.position.lng
        that.lat = data.position.lat
      }
      //定位失败数据
      function onError (err) {
        console.log(err.originMessage)
      }
    }

本地测试谷歌浏览器定位失败,应该和https协议有关;edgn浏览器定位成功,并返回数据

暂时先学习总结这些

举报

相关推荐

0 条评论