基于ts,es6,react函数式组件 使用高德地图

该文介绍如何在React应用中实现高德地图的POI搜索和提示功能,通过封装逻辑获取选址信息。使用了@amap/amap-jsapi-loader进行地图加载,并通过AMap插件处理地图交互,包括地址解析、位置选择器等,需要申请高德地图的APIkey并配置window._AMapSecurityConfig。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现了高德地图的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 否则对应的地图插件无法使用

这里使用的是异步加载插件的方式 更多的插件使用可以参考官网,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值