javascript - Using Baidu map in vue prompts that it cannot be parsed
阿神
阿神 2017-05-19 10:45:45
0
2
1176

I use vue-cli to build the application

Quote the script of Baidu Map in index.html,
[<script type="text/javascript" src="http://api.map.baidu.com/api?...My ak"></script>】

Then call the demo of Baidu Map in the mounted function of app.vue
[

 // 百度地图API功能
var map = new BMap.Map("allmap");    // 创建Map实例
map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);  // 初始化地图,设置中心点坐标和地图级别
map.addControl(new BMap.MapTypeControl());   //添加地图类型控件
map.setCurrentCity("北京");          // 设置地图显示的城市 此项是必须设置的
map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放

The prompt information is as follows screenshot

Then I directly quoted the script of Baidu Map on my own page without using vue-cli, and it can be displayed correctly

I don’t know if anyone else has encountered this problem

阿神
阿神

闭关修行中......

reply all(2)
刘奇

https://www.talkingcoder.com/... Use asynchronous loading of maps

曾经蜡笔没有小新

Global references need to be added in webpack.base.conf.js

webpackConfig

externals: {
   "BMap": "BMap" 
  }, 

This is loaded globally, so it will be loaded regardless of whether you use it or not.

We started with a global approach, and later adopted asynchronous loading considering user experience.

You can use the writing method above, because nodejs is not sophisticated, so I used the callback method

 "http://api.map.baidu.com/api?v=2.0&ak="+ak+"&callback=init";

You can see that there is a callback at the end of the Baidu js link, which will call a function under the window. Then we can register a function and initialize it directly

mounted(){
    window['init']=function(){
    //百度地图加载完成会调用这里,这里就可以正常初始化了
    }
}

If you use the above method, only one Baidu map can be initialized for each page. If there are multiple maps, they need to be locked.

When initializing the first map, since the component needs to be loaded asynchronously, it is locked at this time. The second and third maps do not need to load the component asynchronously. They only need to register the callback function and store the function name in a cookie or local Storage etc. Then when the map is loaded, the first registered callback function will be executed, and then the first one can initialize the map normally. At the same time, the notification reads the other two function names from the storage and calls them to complete the initialization, so that the same page can be initialized multiple times at the same time

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template