1. 程式人生 > >在React 中使用百度地圖,高德地圖出現'AMap' is not defined 'BMap' is not defined

在React 中使用百度地圖,高德地圖出現'AMap' is not defined 'BMap' is not defined

在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',
  }
}
成功