在React中使用百度地圖
阿新 • • 發佈:2018-12-10
首先需要修改index.html檔案:
在index.html中新增百度地圖的呼叫介面
由於react工程是由腳手架建立的即create-react-app建立的。
因此只需要修改node_modules檔案下面的webpack.config.dev.js檔案即可
下面就可以使用了:
使用demo:
import React, { Component } from 'react';
import BMap from 'BMap';
import './App.css';
class App extends Component {
componentDidMount () {
var map = new BMap.Map("mapContainer"); // 建立Map例項
map.centerAndZoom(new BMap.Point(116.404, 39.915), 11); // 初始化地圖,設定中心點座標和地圖級別
map.addControl(new BMap.MapTypeControl()); //新增地圖型別控制元件
map.setCurrentCity("北京"); // 設定地圖顯示的城市 此項是必須設定的
map.enableScrollWheelZoom(true); //開啟滑鼠滾輪縮放
}
render() {
return (
<div >
<div className="mapContainer" id="mapContainer"></div>
</div>
);
}
}
export default App;
效果如下:
補充:注意在react中使用百度地圖的API時會傳入大寫的變數名,這時要使用window.變數名,來表明它是全域性變數。