美文网首页
vue异步调用百度地图

vue异步调用百度地图

作者: 饼饼_佳 | 来源:发表于2017-07-08 21:14 被阅读0次

    Vue 异步调用百度地图

    新建一个map.js

    • 在src/assets创建一个map.js
    export function MP(ak) {
        return new Promise(function(resolve, reject) {
            window.onload = function() {
                resolve(BMap)
            }
            if(!window.BMap){
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = "http://api.map.baidu.com/api?v=2.0&ak=" + ak + "&callback=init";
                script.onerror = reject;
                document.head.appendChild(script);
            }
    
        })
    }
    
    

    在你的百度地图页面中调用

    • 在组件中导入
    import {
        MP
    } from '@/assets/map'
    
    • 在组件中使用
    mounted: function() {
        var that = this;
        this.$nextTick(function() {
            MP('ak') //ak改成你的ak
                .then(BMap => {
                    var geolocation = new BMap.Geolocation();
                    geolocation.getCurrentPosition(function(r) {
                        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                            var lon = r.point.lng
                            var lat = r.point.lat
                            var point = new BMap.Point(lon, lat);
                            // 根据坐标得到地址描述
                            var myGeo = new BMap.Geocoder();
                            myGeo.getLocation(point, function(result) {
                                var city = result.addressComponents.city;
                                var prov = result.addressComponents.province;
                                that.location = city
                                that.lng = lat + ',' + lon
                                that.prov = prov
                                if (city) {
                                    that.location = city
                                } else {
                                    that.location = '定位失败'
                                }
                            });
                        }
                    }, {
                        enableHighAccuracy: true
                    })
                })
        })
    },
    

    推荐一个百度地图的 插件 (vue-baidu-map

    https://github.com/Dafrok/vue-baidu-map

    相关文章

      网友评论

          本文标题:vue异步调用百度地图

          本文链接:https://www.haomeiwen.com/subject/lupjhxtx.html