1、组件配置
import { useEffect, useState, useRef } from 'react';
import Map from '@/pages/SandTable/components/Map';
import { Radio } from 'antd';
export default (props) => {
const { detailData, id } = props;
const [map, setMap] = useState(null);
const [active, setActive] = useState('driver');
const [mapRef, setMapRef] = useState(null);
const mapConfig = () => {
const map = new AMap.Map(`map${id}`, {
zoom: 8, //设置地图显示的缩放级别
expandZoomRange: true,
//pitch: 45,
center: [116.397428, 39.90923],
//mapStyle: 'amap://styles/a9cd8d0e5e7600e36d250b994db36184', //设置地图的显示样式,几种深色'grey','dark','blue','darkblue'
viewMode: '3D', //设置地图模式]
// content: markerContent,
});
setMap(map);
};
const drawMarker = (map) => {
map.clearMap();
const { latitude, longitude } = detailData;
const marker = new AMap.Marker({
position: [+longitude, +latitude], //[+longitude, +latitude],
map,
});
marker.setLabel({
offset: new AMap.Pixel(0, -15), //设置文本标注偏移量
direction: 'top', //设置文本标注方位
content: `<div style="position: relative;color: #fff;background:rgba(0,0,0,.7);padding: 12px;border-radius:6px">
<div>场所:${detailData.name || '--'}</div>
<div style="margin-top: 8px">所属网格:${detailData.grid || '--'}</div>
<div style="position:absolute;bottom:-1px;transform: rotate(135deg) translateX(50%);left:50%;width: 10px;height: 10px;background: conic-gradient(from 90deg at 0 0, rgba(0,0,0,.7) 0, rgba(0,0,0,.7) 45deg, transparent 45.1deg)"></div>
</div>`, //设置文本标注内容
});
map.setFitView();
setMap(map);
};
//构造路线导航类
const drivingFunc = (map, active) => {
console.log(mapRef);
// 根据起终点经纬度规划驾车导航路线
map.clearMap();
const name =
active === 'driver'
? 'AMap.Driving'
: active === 'transfer'
? 'AMap.Transfer'
: 'AMap.Walking';
const v = {
map: map,
panel: 'panel',
hideMarkers: true,
};
if (active === 'transfer') {
v.city = '北京市';
}
dev(name, active, v);
map.setFitView();
setMap(map);
};
const dev = (name, active, v) => {
map.plugin(name, function () {
const driving =
active === 'driver'
? new AMap.Driving(v)
: active === 'transfer'
? new AMap.Transfer(v)
: new AMap.Walking(v);
setMapRef({
ele: driving,
});
driving.search(
new AMap.LngLat(116.379028, 39.865042),
new AMap.LngLat(116.427281, 39.903719),
function (status, result) {
// result 即是对应的驾车导航信息,相关数据结构文档请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
if (status === 'complete') {
console.log(`绘制${active}路线完成`);
console.log(result);
} else {
console.log(`获取${active}数据失败:' + ${result}`);
}
},
);
});
};
useEffect(() => {
const { latitude, longitude } = detailData;
if (latitude && longitude && map) {
drawMarker(map);
}
}, [detailData, map]);
const config = [
{ name: '驾车', key: 'driver' },
{ name: '公交', key: 'transfer' },
{ name: '步行', key: 'walk' },
];
useEffect(() => {
if (map) {
mapRef?.ele?.clear();
drivingFunc(map, active);
}
}, [map, active, mapRef?.current]);
return (
<div style={{ height: '100%', overflow: 'hidden' }}>
<Map mapConfig={mapConfig} mapId={`map${id}`} />
<div style={{ width: '400px', position: 'absolute', top: '200px', left: '0', zIndex: '99' }}>
<Radio.Group
value={active}
onChange={({ target }) => setActive(target.value)}
buttonStyle="solid"
>
{config.map((item) => (
<Radio.Button key={item.key} value={item.key}>
{item.name}
</Radio.Button>
))}
</Radio.Group>
</div>
<div
id="panel"
style={{ width: '400px', position: 'absolute', top: '0', right: '0', zIndex: '99' }}
></div>
</div>
);
};
2、地图配置
import { useRef, useState, useEffect } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';
import style from './index.less';
const amapKey = '90148423e6a88b2a18b76e6ab238ec1c';
export default (props) => {
const { mapConfig, mapId } = props;
useEffect(() => {
window._AMapSecurityConfig = {
securityJsCode: '0b1e150db2cb4d65c7c511b314666015',
};
AMapLoader.load({
key: amapKey, // 申请好的Web端开发者Key,首次调用 load 时必填
version: '2.0', // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
Loca: {
version: '2.0.0',
},
plugins: ['AMap.MouseTool'], // 需要使用的的插件列表,如比例尺'AMap.Scale'等
//'plugins': ['AMap.Scale','AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.ToolBar', 'AMap.Weather', 'AMap.MouseTool', 'AMap.CircleEditor', 'AMap.RectangleEditor', 'AMap.DistrictSearch'],
}).then(() => {
mapConfig();
});
}, []);
return <div id={mapId} className={style.mapWrap}></div>;
};
3、父组件配置
<Map detailData={detailData} id={id} />
4、覆盖物配置
import { useEffect, useState, useRef } from 'react';
import Map from '@/pages/SandTable/components/Map';
import { history } from 'umi';
// 获取网格中心点
const getAreaCenter = (lnglatarr) => {
var total = lnglatarr.length;
var X = 0,
Y = 0,
Z = 0;
lnglatarr.map((lnglat) => {
var lng = (lnglat[0] * Math.PI) / 180;
var lat = (lnglat[1] * Math.PI) / 180;
var x, y, z;
x = Math.cos(lat) * Math.cos(lng);
y = Math.cos(lat) * Math.sin(lng);
z = Math.sin(lat);
X += x;
Y += y;
Z += z;
});
X = X / total;
Y = Y / total;
Z = Z / total;
var Lng = Math.atan2(Y, X);
var Hyp = Math.sqrt(X * X + Y * Y);
var Lat = Math.atan2(Z, Hyp);
return new AMap.LngLat((Lng * 180) / Math.PI, (Lat * 180) / Math.PI);
};
const coverStyle = {
strokeColor: 'rgba(140,191,237,1)',
strokeOpacity: 1,
strokeWeight: 2,
strokeOpacity: 1,
fillColor: 'rgba(194,220,242,1)',
fillOpacity: 0.4,
// 线样式还支持 'dashed'
strokeStyle: 'solid',
// strokeStyle是dashed时有效
// strokeDasharray: [10, 5],
};
export default (props) => {
const {listdata,eventSource,id} = props;
const [active, setActive] = useState('marker');
const [map, setMap] = useState(null);
const activeRef = useRef('marker');
const [eventString, setEventString] = useState('');
const [pathData, setPathData] = useState([]);
const overlays = useRef([]);
const mapConfig = () => {
const map = new AMap.Map(`map${id}`, {
zoom: 8, //设置地图显示的缩放级别
expandZoomRange: true,
//pitch: 45,
center: [115.858227, 28.698179],
//mapStyle: 'amap://styles/a9cd8d0e5e7600e36d250b994db36184', //设置地图的显示样式,几种深色'grey','dark','blue','darkblue'
viewMode: '3D', //设置地图模式]
// content: markerContent,
});
setMap(map);
// drawMarker(map, listdata);
};
/* const center = getAreaCenter(path);
position: [center.lng, center.lat], */
// 画多边形
const drawPolygon = (map, arr) => {
for (let i = 0; i < arr.length; i++) {
const path = pathData;
var polygon = new AMap.Polygon({
path,
...coverStyle,
});
map.add([polygon]);
overlays.current.push(polygon);
map.setFitView();
setMap(map);
}
};
const drawMarker = (map, arr) => {
// console.log(map, 'dra');
map.clearMap();
for (let i = 0; i < arr.length; i++) {
const center = getAreaCenter(pathData);
var marker = new AMap.Marker({
position: [center.lng, center.lat], // 经纬度对象,也可以是经纬度构成的一维数组[116.39, 39.9]
//latitude,longitude
map: map,
content: `
<div class="gridmarkercontainer">
<div class="my_marker bgred">
<div class="marker">
</div>
</div>
<div class="label">${arr[i].name}<div>
<div> `,
offset: new AMap.Pixel(-60, -30), // 设置点标记偏移量
// anchor: 'bottom-left', // 设置锚点方位
});
/* marker
.on('mouseover', function (e) {
e.target.dom.children[0].children[0].className = 'my_marker bgblue';
})
.on('mouseout', function (e) {
e.target.dom.children[0].children[0].className = 'my_marker bgred';
})
.on('click', function (e) {
const query = {};
const params = {
id: arr[i].id,
addressType,
type: 'address',
};
if (eventString) {
query.eventSource = eventString;
}
history.push({
pathname: `/analysis-detailed/${params.id}/${params.type}/${
params.addressType || ''
}`,
query,
});
}); */
// 将创建的点标记添加到已有的地图实例:
map.add([marker]);
}
map.setFitView();
setMap(map);
// console.log(arr, map, 'drawer');
};
useEffect(() => {
// console.log(listdata, selectType, '接收');
if (listdata) {
if (listdata[0]?.point) {
const arr = JSON.parse(listdata[0]?.point);
let res = [];
arr.map((item, i) => {
res.push(Object.keys(item).map((k) => item[k]));
});
// console.log(res);
setPathData(res);
}
}
}, [listdata]);
useEffect(() => {
if (map) {
// console.log(map);
// drawPolygon();
if (listdata.length > 0 && pathData?.length > 0) {
drawMarker(map, listdata);
drawPolygon(map, listdata);
} else {
map.clearMap();
}
}
}, [pathData, map]);
useEffect(() => {
if (eventSource && eventSource.length > 0) {
setEventString(eventSource.join(','));
} else {
setEventString(null);
}
}, [eventSource]);
return (
<div style={{ height: '100%', overflow: 'hidden' }}>
<Map mapConfig={mapConfig} mapId={`map${id}`} />
</div>
);
};
data=[{
name:'名字',
point: "[{\"lon\":115.87230665819169,\"lat\":28.725353704157826},{\"lon\":115.8723442091179,\"lat\":28.724982218209263},{\"lon\":115.87244747416497,\"lat\":28.72440554327106},{\"lon\":115.8707952334118,\"lat\":28.724357263508793},{\"lon\":115.87083814875604,\"lat\":28.724866883221623},{\"lon\":115.87090520398141,\"lat\":28.72533626979923},{\"lon\":115.87119488255502,\"lat\":28.72532419985866},{\"lon\":115.87230665819169,\"lat\":28.725353704157826}]",
}]
5、画线
const lineArr = [
[116.478935, 39.997761],
[116.478939, 39.997825],
[116.478912, 39.998549],
[116.478912, 39.998549],
[116.478998, 39.998555],
[116.478998, 39.998555],
[116.479282, 39.99856],
[116.479658, 39.998528],
[116.480151, 39.998453],
[116.480784, 39.998302],
[116.480784, 39.998302],
[116.481149, 39.998184],
[116.481573, 39.997997],
[116.481863, 39.997846],
[116.482072, 39.997718],
[116.482362, 39.997718],
[116.483633, 39.998935],
[116.48367, 39.998968],
[116.484648, 39.999861],
];
// 绘制线方法
const drawPolyline = (map) => {
map.clearMap();
// 绘制轨迹
var polyline = new AMap.Polyline({
map: map,
path: lineArr,
showDir: true, //方向箭头
strokeColor: '#28F', //线颜色
// strokeOpacity: 1, //线透明度
strokeWeight: 6, //线宽
// strokeStyle: "solid" //线样式
});
map.add([polyline]);
map.setFitView();
setMap(map);
};
//
useEffect(() => {
if (map) {
mapRef?.ele?.clear();
// drivingFunc(map, active);
drawPolyline(map);
}
}, [map, active, mapRef?.current]);