antdesign框架如何使用高德地图(搜索)

首先需要在项目中引入高德地图的JS API,可以在官网上申请并获取API key进行使用。具体步骤如下:

  1. 安装高德地图的JS API,可以通过npm安装:
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 (
    <div>
      <div
        style={{
          width: '100%',
          display: 'flex',
          justifyContent: 'space-between',
          height: '50px',
        }}
      >
        <Input
          style={{ width: '60%', height: '30px' }}
          value={keyword}
          onChange={(e) => {
            setKeyword(e.target.value);
          }}
          id="map"
        />
        <Button onClick={search} disabled={!keyword}>
          搜索
        </Button>
      </div>

      <div id="container" className="map" style={{ height: '400px', borderRadius: '5px' }}></div>
    </div>
  );
};

export default MapComponent;

     3.在需要的地方引用

import MapComponent from './map';

     4.在指定的html中放入

<MapComponent onMapClick={map} />

     5.map事件:

//地图事件
  const map = (lng, lat, addresss) => {
    setLng(lng);
    setLat(lat);
    setAddress(addresss);
  };

代码中使用了useEffectuseRef钩子分别进行地图的初始化和搜索操作,通过AMapLoader.load方法加载高德地图JS API并初始化地图,创建搜索对象和搜索按钮,并给搜索按钮绑定点击事件,当点击搜索按钮时触发搜索操作。在代码中还使用了Ant Design中的InputButton组件作为搜索界面的元素。

需要注意的是,使用高德地图API需要先申请API key,并在代码中传入。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TechWhiz-晓同

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值