干貨,無話
1、react-create-app,創建新react項目;
2、npm install react-amap,引入高德地圖的封裝;
3、編寫組件index.js:
import React from "react";
import ReactDOM from "react-dom";
import Map from "./Map3";
let mapData = {
city: "北京",
mapCenter:[116.418261, 39.921984], //城市定位,經緯度定位只能選擇1個
mapZoom: 10, //地圖縮放
mapKey: '12345678d98aff1166e51962f108bb24', //你的高德key
status: { //是否支持放大拖拽
zoomEnable: true,
dragEnable: true,
},
mapMaker :[ //marker標記點(list)
{lnglat:[116.401728,39.911984],text:'要顯示的內容1'},
{lnglat:[116.436691,39.921984],text:'要顯示的內容2'}
],
plugins:['ToolBar']
};
ReactDOM.render(
<div style ={{width:"100%",height:"100%"}}>
<Map title="map" mapData={mapData}/>
</div>,
document.getElementById("root")
);
注意render方法內引用了Map組件,因此要編寫一個Map3.js,提供這個組件
4、編寫Map3.js組件
import React, { Component } from "react";
import { Map, Marker } from 'react-amap';
import ZoomCtrl from './zoom';
class WebMap3 extends Component {
constructor(props) {
super(props);
this.data = props;
//地圖事件
this.amapEvents = {
created: (mapInstance) => {
var marker = new AMap.Marker({
// 經緯度對象,也可以是經緯度構成的一維數組[116.39, 39.9]
position: new AMap.LngLat(116.39, 39.9),
title: '北京!!'
});
mapInstance.add(marker);
}
};
//點位事件
this.markerEvents = {
click: (markerInstance) => {
this.Position = [markerInstance.lnglat.lng,markerInstance.lnglat.lat];
this.setState({
isShow: true,
});
}
};
}
render() {
let {city, mapCenter, mapZoom, mapKey, status, plugins} = this.data.mapData;
return (
<div style ={{width:"100%",height:"95%"}}>
<Map amapkey={mapKey} city={city} zoom={mapZoom} center={mapCenter} status={status} plugins={plugins} events={this.amapEvents}>
{this.data.mapData.mapMaker.map((comment) => (
<Marker position={comment.lnglat} events={this.markerEvents}>
</Marker>
))}
<ZoomCtrl />
</Map>
</div>
);
}
}
export default WebMap3;
注意標紅部分,會報錯

這個是關鍵! 有兩個辦法解決,分別見下面的5.1和5.2
5、解決react下找不到原生高德地圖AMap類的問題
5.1 方法1
暴力手段,直接搞定。
使用注釋 //eslint-disable-next-line 寫在每個出現AMap類的前面一行,如下所示

原理是告訴eslint:注釋下面這一行您別管。
5.2 方法2
強迫症手段,分為3步。
5.1.1 在項目根目錄下新加.eslintrc.js文件,把AMap變量放到globals集合里面
module.exports = {
"env": {
"browser": true,
"es6": true
},
// 腳本在執行期間訪問的額外的全局變量
// 當訪問未定義的變量時,no-undef 規則將發出警告。
// 如果你想在一個文件里使用全局變量,推薦你定義這些全局變量,這樣 ESLint 就不會發出警告了。
// 你可以使用注釋或在配置文件中定義全局變量
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly",
"AMap":true,
"window":true,
"document":true,
},
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 2018,
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
"semi": ["error","always"],
}
};
注意紅色部分代碼表示:AMap是個全局變量,是webpack我罩着的,保證能用,eslint你別管。
當然,webpack.config.js要做點修改,以支持我們剛寫的.eslintrc.js文件。可是react-create-app生成的項目的webpack.config.js不好找啊,也能找到:
5.2.2 修改 node_modules\react-scripts\config\webpack.config.js文件
在這個文件搜索字符串 useEslintrc, 大概在webpack.config.js文件的第326行,把 useEslintrc: false, 改成 useEslintrc: true, 然后保存。如下所示:

5.2.3 完工
呃
6 驗收
在控制台運行npm start,然后訪問http://localhost:3000,出現下圖表示OK!

7 總結
此方法適用於在react中調用jquery、百度地圖、高德地圖、OpenLayer、echart等等使用ES5編寫的各類控件庫。
