nuxt项目以及vue项目中使用百度地图api

Question?如何在nuxt项目以及vue项目中使用百度地图api以及高德api?
1/**新建map.js脚本**/
/**注意nuxt项目中此脚本放在plugins目录**/
if(process.browser){
  !function (mapInit) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://api.map.baidu.com/api?v=2.0&ak=百度api获取你的密钥&callback=mapinit";
    window['mapinit'] = function () {
      mapInit();
    };
    document.head.appendChild(script);
  }(function () {
    // 这里使用BMap
    var map = new BMap.Map("allmap");
    map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);
    var local = new BMap.LocalSearch(map, {
      renderOptions: { map: map }
    });
    local.search("宋家庄地铁站");
  });
}
2 /**引用在你要使用的页面中**/
nuxt引用方式==》import map from "@/plugins/map.js";
vue引用方式==》import map from "../../static/map.js";

1/**下面是引用高德地图**/
/**注意vue项目中此脚本放在static目录**/
export default function MapLoader() {
    return new Promise((resolve, reject) => {
        if (window.AMap) {
            resolve(window.AMap)
        } else {
            // 创建script标签并放入cdn链接
            var script = document.createElement("script")
            script.type = "text/javascript"
            script.async = true
            script.src = "https://webapi.amap.com/maps?v=1.3&key=1721fe46ba6e4967156c2cab078d89da&callback=initAMap"
            script.onerror = reject
            document.head.appendChild(script)
        }
        window.initAMap = () => {
            // 注入相关插件
            window.AMap.plugin(["AMap.ToolBar", "AMap.CircleEditor", "AMap.PolyEditor"], function () {
                //异步同时加载多个插件
                var toolbar = new AMap.ToolBar();
                map.addControl(toolbar);
            });
            // 将结果抛出
            resolve(window.AMap)
        }
    })
}
2页面中引用import MapLoader from "@/plugins/aMap.js";
3调用方法
  let that = this;
     console.log("高德地图");
  MapLoader().then(AMap => {
    that.map = new AMap.Map("allmap", {
    center: [116.423161,39.841029],
    zoom: 13
  }).catch(error => {
    console.log("地图加载失败",error)
  })
  })

 

你可能感兴趣的:(nuxt)