vue.js 高德地图

AMap.js

module.exports = function (k) {
    return new Promise(function (resolve, reject) {
        window.initTheMap = function () {
            resolve(AMap)
        }

        var script = document.createElement('script')
        script.type = 'text/javascript'
        script.async = true
        script.src = 'http://webapi.amap.com/maps?v=1.3&callback=initTheMap&key=' + k
        //script.onload = resolve
        script.onerror = reject
        document.head.appendChild(script)
    })
}

AMap.vue

<template>
    <div></div>
</template>
<script>
    var mapLoader = require('./AMap.js')

    module.exports = {
        replace: true,
        ready() {
            var self = this

            mapLoader('bfe31f4e0fb231d29e1d3ce951e2c780').then(AMap => {
                self.map = new AMap.Map(self.$el, {
                    resizeEnable: true,
                    zoom: 12,
                })

                self.map.on('click', function (e) {
                    self.$dispatch('map-click', e)

                    if (!self.marker) {
                        self.marker = new AMap.Marker({ map: self.map })
                    }

                    self.marker.setPosition([e.lnglat.getLng(), e.lnglat.getLat()])
                })

                self.$nextTick(function () {
                    self.$dispatch('ready', self.map)
                })
            })
        }
    }
</script>

app.vue

<template>
    <gd-map @ready="ready" :style='{ height:"400px" }'></gd-map>
</template>

<script>
    module.exports = {
        components: {
            gdMap: require('./AMap.vue')
        },
        methods: {
            ready(map) {
                console.log('ready', map)
            }
        }
    }
</script>
    原文作者:Chobits
    原文地址: https://segmentfault.com/a/1190000006703063
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞