先吐嘈一下,现在在网上寻找解决问题的方法,基本上都是重复的回答,让人蛋疼,CV的人太多了,以下解决方法一,这个回答最基尔多,搜索下来,一页的回答全是这个,真是日了狗了
用react开发项目时,需要用到高德地图,但遇到错误:AMap is not defined
根据你实际用到的场景有以下解决方法(我自己是用的解决方法五):
解决方法一
index.html
<script type="text/javascript"
src="http://api.map.baidu.com/api?v=2.0&ak=你的key"></script>
<script src="http://webapi.amap.com/maps?v=1.4.0&key=你的key"></script>
demo.js
import BMap from 'BMap'
import AMap from 'AMap'
// 高德地图
let center = [longitude, latitude]
let map = new AMap.Map('allmap', {
center: center,
resizeEnable: true,
zoom: 17
})
new AMap.Marker({
position: center,
map: map,
icon: new AMap.Icon({
size: new AMap.Size(40, 50),
image: iconImg,
imageOffset: new AMap.Pixel(0, 0 - 0 * 25)
}),
offset: new AMap.Pixel(-20, -40)
})
//百度地图
let map = new BMap.Map('allmap');
console.log(map)
let point = new BMap.Point(longitude, latitude);
map.centerAndZoom(point, 17); // 初始化地图,设置中心点坐标和地图级别
map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
let myIcon2 = new BMap.Icon(iconImg,
new BMap.Size(40, 40), {
offset: new BMap.Size(10, 25),
imageOffset: new BMap.Size(0, 0 - 0 * 25)
});
let myP2Marker = new BMap.Marker(point, {icon: myIcon2});
myP2Marker.setOffset(new BMap.Size(0, -20));
map.addOverlay(myP2Marker);
出现’AMap’ is not defined ‘BMap’ is not defined
在config/webpack.config.dev.js
module.exports = {
//entry
//output等
//加入
externals: {
'BMap': 'BMap',
'AMap': 'AMap',
}
}
解决方法二:
将 index.html中引入的script 放入 body标签里面
解决方法三:
地址http 要改成https
解决方法四
引入react-amap
解决方法五
我用以上方法都没有解决AMap is not defined 的问题,我经过查看代码,思考其原理,知道是渲染方面的问题造成的,后来尝试一系列解决方法,都没能成功,冥思之下,突然灵光乍现,想到了setTimeout来解决,让AMap延迟一下就可以了。
最后完美解决。