以下是一个基于 React 的输入地址高德逆编码组件的封装示例:

import React, { useState, useEffect } from 'react';
import { Input } from 'antd';
import axios from 'axios';

const AMapGeocoder = ({ value, onChange }) => {
  const [address, setAddress] = useState(value || '');

  useEffect(() => {
    setAddress(value);
  }, [value]);

  const handleAddressChange = (e) => {
    const inputValue = e.target.value;
    setAddress(inputValue);
    if (inputValue) {
      axios
        .get(`https://restapi.amap.com/v3/geocode/geo?key=YOUR_AMAP_API_KEY&address=${inputValue}`)
        .then((response) => {
          const { geocodes } = response.data;
          const location = geocodes[0].location.split(',');
          onChange({ address: inputValue, location });
        })
        .catch((error) => {
          console.error(error);
        });
    } else {
      onChange({ address: '', location: [] });
    }
  };

  return (
    <Input
      placeholder="请输入地址"
      value={address}
      onChange={handleAddressChange}
    />
  );
};

export default AMapGeocoder;

这个组件接受两个 props:valueonChange,其中 value 为当前输入框中的值,onChange 是一个回调函数,当输入框中的值改变时调用,函数的参数是一个对象,包含了当前输入框中的地址 address 和地址对应的经纬度 location

handleAddressChange 函数中,我们使用 axios 发送一个 GET 请求到高德地图的逆编码 API,获取地址对应的经纬度。如果地址为空,则直接调用 onChange 函数,将地址和经纬度都设为空数组。

最后,我们返回一个带有默认 placeholder 和传入的 value 的输入框,并将 handleAddressChange 函数绑定到 onChange 事件上


原文地址: http://www.cveoy.top/t/topic/eYJj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录