horshoo
horshoo
发布于 2个月前

在React 中使用百度地图,高德地图出现'AMap' is not defined 'BMap' 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',
  }
}

成功!!!