vue中引入高德地图

总的来说,vue组件中使用高德地图的方式有两种,一种是vue-amap :一套专门用于vue的高德地图插件;另外一种是原生的高德地图。

方式一、vue-amap:

官网API:直达车

(1)、安装依赖:

npm install vue-amap -S

或者淘宝镜像:

cnpm install vue-amap -save

亦或(CDN的方式获取最新版本的资源):

<script src="https://unpkg.com/vue-amap/dist/index.js"></script>

(2)、按需引入:(单个组件中使用没必要占用资源在main.js中引用)

其中密钥申请的位置:key

import VueAMap from 'vue-amap';
Vue.use(VueAMap);
 // 初始化高德地图的 key 和插件
VueAMap.initAMapApiLoader({
  key: 'c76c4e9a861fe1f715c48d893d07116b',
  plugin: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.CircleEditor'],
  v: '1.4.4'
});

(3)、创建地图实例:

(4)、完整代码:

<template>
    <div class="amap-page-container">
      <el-amap ref="map" vid="amapDemo" :amap-manager="amapManager" :center="center" :zoom="zoom" :plugin="plugin" :events="events" class="amap-demo">
      </el-amap>

      <div class="toolbar">
        <button @click="getMap()">get map</button>
      </div>
    </div>
  </template>

  <style>
    .amap-demo {
      height: 300px;
    }
  </style>

  <script>
    // NPM 方式
    // import { AMapManager } from 'vue-amap';
    // CDN 方式
    let amapManager = new VueAMap.AMapManager();
    module.exports = {
      data: function() {
        return {
          amapManager,
          zoom: 12,
          center: [121.59996, 31.197646],
          events: {
            init: (o) => {
              console.log(o.getCenter())
              console.log(this.$refs.map.$$getInstance())
              o.getCity(result => {
                console.log(result)
              })
            },
            'moveend': () => {
            },
            'zoomchange': () => {
            },
            'click': (e) => {
              alert('map clicked');
            }
          },
          plugin: ['ToolBar', {
            pName: 'MapType',
            defaultType: 0,
            events: {
              init(o) {
                console.log(o);
              }
            }
          }]
        };
      },

      methods: {
        getMap() {
          // amap vue component
          console.log(amapManager._componentMap);
          // gaode map instance
          console.log(amapManager._map);
        }
      }
    };
</script>

效果:

扫描二维码关注公众号,回复: 10619066 查看本文章

方式二:SDK原生的方式引入高德地图:

(1)申请密钥key:密钥申请直通车

(2)vue.config.js中引入:

module.exports = {
    // 是否为生产环境构建生成 source map?
    productionSourceMap: false,
    configureWebpack: {
        externals: {
            "AMap": "AMap"
        }
    },
    // webpack-dev-server 相关配置
    devServer: {
        // host: "localhost",
        open: true,
        port: 8001,
        overlay: {
            errors: false,
            warnings: false
        }
    }
}
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=ec817c7d9a73dae44ddbb3eb9d032a33"></script>

(3)、完整代码:

<template>
		<section>		
				<div id="container" style="width:100%; height:680px; margin-top: 20px"></div>
		</section>
</template>

<script>
    import AMap from 'AMap'
    export default {
        name: "home",
        data() {
            return {

            }
        },
        methods: {
            init() {
                var map = new AMap.Map('container', {
                    resizeEnable: true,
                })
                AMap.plugin(['AMap.ToolBar', 'AMap.OverView', 'AMap.MapType', 'AMap.Scale', 'AMap.Geolocation'], function () { //异步加载插件
                    var geolocation = new AMap.Geolocation({
                        // 是否使用高精度定位,默认:true
                        enableHighAccuracy: true,
                        // 设置定位超时时间,默认:无穷大
                        timeout: 10000,
                        // 定位按钮的停靠位置的偏移量,默认:Pixel(10, 20)
                        buttonOffset: new AMap.Pixel(10, 20),
                        // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
                        zoomToAccuracy: true,
                        // 定位按钮的排放位置, RB表示右下
                        buttonPosition: 'RB'
                    })
                    map.addControl(new AMap.ToolBar());
                    map.addControl(new AMap.OverView());
                    map.addControl(new AMap.MapType());
                    map.addControl(new AMap.Scale());
                    map.addControl(geolocation);
                    geolocation.getCurrentPosition();
                    AMap.event.addListener(geolocation, 'complete', (e) => {
                        // console.log(e) // 定位成功之后做的事
                        // 定位成功之后再定位处添加一个marker
                        var marker = new AMap.Marker({
                            position: [e.position.lng, e.position.lat], // (e.position)--->定位点的点坐标, position ---> marker的定位点坐标,也就是marker最终显示在那个点上,
                        })
                        map.add(marker);
                    })
                })

                var geocoder, marker;

                function regeocoder(lnglatXY, that) {
                    AMap.plugin('AMap.Geocoder', function () {
                        var geocoder = new AMap.Geocoder({
                            radius: 1000,
                            extensions: "all"
                        });
                        geocoder.getAddress(lnglatXY, function (status, result) {
                            if (status === 'complete' && result.info === 'OK') {
                                var address = result.regeocode.formattedAddress;
                                that.ruleForm.addr = address;
                                // let contentString = '<div class="cafe-info-window">' +
                                //     '<div class="cafe-name">' + result.regeocode.addressComponent.province + result.regeocode.addressComponent.city + '</div>' +
                                //     '<div class="cafe-address">' +
                                //     '<span class="street">' + result.regeocode.addressComponent.district + '</span>' +
                                //     '<span class="city">' + result.regeocode.addressComponent.township + '</span> ' +
                                //     '<span class="state">' + result.regeocode.addressComponent.street + '</span>'
                                // '</div>' +
                                // '</div>'
                                // let contentString = result.regeocode.formattedAddress;
                                // var infoWindow = new AMap.InfoWindow({
                                //     content: contentString//信息窗体的内容
                                // })
                                // infoWindow.open(map, marker.getPosition()); //信息窗体打开
                            }
                        });
                        if (!marker) {
                            marker = new AMap.Marker();
                            map.add(marker);
                        }
                        marker.setPosition(lnglatXY);
                    })
                }


                var that = this
                map.on('click', function (e) {
                    var lnglatXY = [e.lnglat.getLng(), e.lnglat.getLat()];
                    regeocoder(lnglatXY, that)
                    that.ruleForm.long = e.lnglat.getLng()
                    that.ruleForm.lat = e.lnglat.getLat();
                });
            },
        },

        mounted() {

        },

        activated() {
            this.init();
        },

        deactivated() {
         
        }
    }
</script>

<style scoped>
		* {
				padding: 0;
				margin: 0;
		}

		#map {
				margin-top: 20px;
				height: 680px;
		}
</style>

效果:

朋友,你想知道vue中怎么使用百度地图吗,请看:

vue+element中引入百度地图

发布了128 篇原创文章 · 获赞 250 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/XU441520/article/details/103778251