在Vue中使用高德地图,查询地址从附近开始显示可以按照以下步骤进行操作:

  1. 在Vue项目中安装 vue-amap 库:

    npm install vue-amap --save
    
  2. main.js 文件中引入 vue-amap 库,并初始化高德地图:

    import VueAMap from 'vue-amap';
    
    Vue.use(VueAMap);
    VueAMap.initAMapApiLoader({
      key: 'your_amap_api_key', // 替换为自己的高德地图API Key
      plugin: ['AMap.Geolocation']
    });
    
  3. 在需要使用地图的组件中,添加地图容器和相关代码:

    <template>
      <div>
        <div id="mapContainer"></div>
      </div>
    </template>
    
    <script>
    export default {
      mounted() {
        this.initMap();
      },
      methods: {
        initMap() {
          // 创建地图
          const map = new window.AMap.Map('mapContainer', {
            zoom: 15 // 地图缩放级别
          });
    
          // 获取当前位置
          map.plugin('AMap.Geolocation', function() {
            const geolocation = new window.AMap.Geolocation({
              enableHighAccuracy: true, // 是否使用高精度定位,默认:true
              timeout: 10000, // 超过10秒后停止定位,默认:无穷大
              maximumAge: 0, // 定位结果缓存0毫秒,默认:0
              convert: true, // 自动偏移坐标,偏移后的坐标为高德坐标,默认:true
              showButton: false, // 显示定位按钮,默认:true
              buttonPosition: 'LB', // 定位按钮停靠位置,默认:'LB',左下角
              buttonOffset: new window.AMap.Pixel(10, 20), // 定位按钮距离右下角50px,向上20px偏移
              showMarker: false, // 定位成功后在定位到的位置显示点标记,默认:true
              showCircle: false, // 定位成功后用圆圈表示定位精度范围,默认:true
              panToLocation: true, // 定位成功后将定位到的位置作为地图中心点,默认:true
              zoomToAccuracy: true // 定位成功后调整地图视野范围使定位位置及精度范围视图呈现,默认:false
            });
    
            map.addControl(geolocation);
            geolocation.getCurrentPosition(function(status, result) {
              if (status === 'complete') {
                // 定位成功,显示附近位置
                map.setCenter([result.position.lng, result.position.lat]);
                map.plugin('AMap.PlaceSearch', function() {
                  const placeSearch = new window.AMap.PlaceSearch({
                    type: '', // 兴趣点类型
                    pageSize: 10, // 单页显示结果数量
                    pageIndex: 1, // 页码
                    city: '', // 兴趣点所在城市
                    citylimit: true, // 是否强制限制在设置的城市内搜索
                    map: map, // 展现结果的地图实例
                    panel: 'panel' // 结果列表将在此容器中进行展示
                  });
                  placeSearch.searchNearBy('餐馆', [result.position.lng, result.position.lat], 1000); // 查询附近的餐馆
                });
              } else {
                // 定位失败
                console.log(result);
              }
            });
          });
        }
      }
    };
    </script>
    
    <style>
    #mapContainer {
      width: 100%;
      height: 400px;
    }
    </style>
    

通过以上步骤,就可以在Vue中使用高德地图,并在地图上显示附近的餐馆位置

vue 中使用高德地图查询地址从附近开始显示

原文地址: https://www.cveoy.top/t/topic/iMhM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录