8

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
7.4k 声望171 粉丝

保卫骡博 Chobits#3780