实现了高德地图的POI搜索与搜索提示功能 ,封装了逻辑可以传出选址的一些信息
需要自己去申请高德地图的key https://console.amap.com/dev/key/app
根据官网的步骤即可完成
首先需要自己安装对应依赖 这里使用的umi 框架 很方便
npm i @amap/amap-jsapi-loader --save 使用npm引入高德地图
import React, { LegacyRef, useEffect, useRef } from 'react';
import { message, Input } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import AMapLoader from '@amap/amap-jsapi-loader';
import './Map.less';
// 编辑地图 传出选址的位置信息 经纬度 code 地址名 新增或修改
type GmapType = {
LngLat?: [] as Number; //经纬度 如果为undefined 则为新增 否则为修改 地图center值为传入的经纬度
getAddressData: (AddressData: {}) => any; //传入方法 获得地址数据
};
export default function GMap(props: GmapType) {
const { LngLat, getAddressData }: any = props;
const analyzeAddress = (result: any) => {
const { lng, lat } = result.position; //经纬度
const { address } = result; //详细地址
const fullAddress = address.slice(address.indexOf('区', '县') + 1);
const { adcode, province, city, district } =
result.regeocode.addressComponent; //地址信息
return {
latitude: lat,
longitude: lng,
fullAddress: fullAddress,
addressName: `${province}-${city}-${district}`,
addressCode: adcode,
};
}; //处理地图中得到的地址结构 满足返回信息的格式
const mapRef = useRef<any>({});
const inputRef = useRef<any>({}); //搜索框
async function loadGMap() {
const AMap = await AMapLoader.load({
key: '申请的key',
version: '2.0',
plugins: [],
AMapUI: {
version: '1.1',
plugins: ['misc/PositionPicker'],
},
});
const map = (mapRef.current.map = new AMap.Map('g-map-container', {
mapStyle: 'amap://styles/fresh',
zoom: 18,
center: LngLat,
lang: 'zh_cn',
viewMode: '3D',
pitch: 30,
resizeEnable: true, //设置缩放
keyboardEnable: false,
}));
AMap.plugin(
['AMap.ToolBar', 'AMap.Scale', 'AMap.AutoComplete', 'AMap.PlaceSearch'],
() => {
map.addControl(new AMap.ToolBar()); //控制缩放
map.addControl(new AMap.Scale()); //比例尺
const autocomplete = new AMap.AutoComplete({
input: inputRef.current.input,
});
const placeSearch = new AMap.PlaceSearch({
map: map,
}); //构造地点查询类
autocomplete.on('select', function (result: any) {
//TODO 针对选中的poi实现自己的功能
placeSearch.search(result.poi.name)
});
},
); //地图插件集的处理
const positionPicker = new AMapUI.PositionPicker({
mode: 'dragMap', //dragMarker设置为不可拖拽
map: map,
});
positionPicker.start(); //设置开拖拽模式
positionPicker.on('success', (result: any) => {
getAddressData(analyzeAddress(result));
}); //成功获得拖拽后周边的结果
positionPicker.on('fail', () => {
message.error('无法获取当前位置信息');
});
}
useEffect(() => {
window._AMapSecurityConfig = {
securityJsCode: 'key对应的密匙',
};
loadGMap();
}, [LngLat]);//当传入的经纬度改变时地图会重新渲染
return (
<>
<div className="mapComponent">
<div id="g-map-search">
<Input
placeholder={`输入地址`}
prefix={<SearchOutlined />}
size="middle"
style={{ width: '250px' }}
ref={inputRef}
/>
</div>
<div id="g-map-container"></div>
</div>
</>
);
}
可以直接更改下逻辑 注意设置window._AMapSecurityConfig 否则对应的地图插件无法使用
这里使用的是异步加载插件的方式 更多的插件使用可以参考官网,