首先需要在项目中引入高德地图的JS API,可以在官网上申请并获取API key进行使用。具体步骤如下:
npm install --save @amap/amap-jsapi-loader
2.新建一个文件名字随便起(map.tsx)
import AMapLoader from '@amap/amap-jsapi-loader';
import { Button, Input } from 'antd';
import { useEffect, useState } from 'react';
import './MapContainer.css';
// import { compact } from 'lodash';
let data = JSON.parse(sessionStorage.getItem('datas'));
const MapComponent = (props) => {
const [map, setMap] = useState({});
const [keyword, setKeyword] = useState('');
const [selectedLocation, setSelectedLocation] = useState({});
const [selectedAddress, setSelectedAddress] = useState('');
useEffect(() => {
window._AMapSecurityConfig = {
securityJsCode: 'a69dcefa5bcfb7647713f4285773aea5', //密钥
};
AMapLoader.load({
key: '2ac9de89b635e0caef82af0edf4248cf',
version: '1.4.15',
plugins: ['AMap.PlaceSearch'],
})
.then((AMap) => {
const mapInstance = new AMap.Map('container', {
viewMode: '2D',
zoom: 11,
center: [data.lng, data.lat],
layers: [new AMap.TileLayer.Satellite(), new AMap.TileLayer.RoadNet()],
});
mapInstance.on('click', (e) => {
const lnglat = e.lnglat;
const lng = e.lnglat.getLng();
const lat = e.lnglat.getLat();
console.log([e.lnglat.lng, e.lnglat.lat]);
setSelectedLocation({ lng, lat });
setSelectedAddress('');
AMap.plugin('AMap.Geocoder', function () {
const geocoder = new AMap.Geocoder({
city: '', // 城市为空表示全国范围内逆地理编码
});
geocoder.getAddress(lnglat, function (status, result) {
if (status === 'complete' && result.regeocode) {
const address = result.regeocode.formattedAddress || '';
setSelectedAddress(address);
console.log(address);
const lng = e.lnglat.getLng();
const lat = e.lnglat.getLat();
props.onMapClick(lng, lat, address);
setKeyword(address);
}
});
});
});
setMap(mapInstance);
})
.catch((e) => {
console.log(e);
});
}, []);
const search = () => {
if (keyword) {
AMapLoader.load({
key: '2ac9de89b635e0caef82af0edf4248cf',
version: '1.4.15',
plugins: ['AMap.PlaceSearch'],
})
.then((AMap) => {
const placeSearch = new AMap.PlaceSearch({
city: '',
map,
});
placeSearch.search(keyword, (status, result) => {
console.log(status, result);
if (status === 'complete' && result.info === 'OK') {
const pois = result.poiList.pois;
if (pois.length > 0) {
const { location } = pois[0];
map.setCenter(location);
}
} else {
console.log('搜索失败或无结果');
}
});
})
.catch((e) => {
console.log(e);
});
}
};
return (
{
setKeyword(e.target.value);
}}
id="map"
/>
);
};
export default MapComponent;
3.在需要的地方引用
import MapComponent from './map';
4.在指定的html中放入
5.map事件:
//地图事件
const map = (lng, lat, addresss) => {
setLng(lng);
setLat(lat);
setAddress(addresss);
};
代码中使用了useEffect
和useRef
钩子分别进行地图的初始化和搜索操作,通过AMapLoader.load
方法加载高德地图JS API并初始化地图,创建搜索对象和搜索按钮,并给搜索按钮绑定点击事件,当点击搜索按钮时触发搜索操作。在代码中还使用了Ant Design中的Input
和Button
组件作为搜索界面的元素。
需要注意的是,使用高德地图API需要先申请API key,并在代码中传入。