react 中使用高德地图的原生 API
干货, 无话
1,react-create-App, 创建新 react 项目;
2,NPM install react-amap, 引入高德地图的封装;
3, 编写组件 index.JS:importReactfrom"react";
importReactDOMfrom"react-dom";
importMapfrom"./Map3";
letmapData={
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(
document.getElementById("root")
);
注意 render 方法内引用了 Map 组件, 因此要编写一个 Map3.JS, 提供这个组件
4, 编写 Map3.JS 组件importReact,{Component}from"react";
import{Map,Marker}from'react-amap';
importZoomCtrlfrom'./zoom';
classwebMap3extendsComponent{
constructor(props){
super(props);
this.data=props;
// 地图事件
this.amapEvents={
created:(mapInstance)=>{
varmarker=newAMap.Marker({
// 经纬度对象, 也可以是经纬度构成的一维数组 [116.39, 39.9]
position:newAMap.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(
{this.data.mapData.mapMaker.map((comment)=>(
))}
);
}
}
exportdefaultWebMap3;
注意标红部分, 会报错
这个是关键! 有两个办法解决, 分别见下面的 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 编写的各类控件库.
来源: https://www.cnblogs.com/zjw0901/p/11103744.html