首先需要引入高德地图的 JavaScript API:

<script src='https://webapi.amap.com/maps?v=1.4.15&key=your_amap_key'></script>

接下来,在 React 中实现输入地址高德地址逆编码的功能,我们可以创建一个组件 AddressInput,其中包含一个输入框和一个按钮:

import React, { useState } from 'react';

const AddressInput = () => {
  const [address, setAddress] = useState('');
  const [location, setLocation] = useState(null);

  const handleSearch = () => {
    const geocoder = new window.AMap.Geocoder({
      city: '全国',
    });
    geocoder.getLocation(address, (status, result) => {
      if (status === 'complete' && result.info === 'OK') {
        const { lng, lat } = result.geocodes[0].location;
        setLocation({ lng, lat });
      } else {
        console.error('根据地址查询位置失败');
      }
    });
  };

  return (
    <div>
      <input value={address} onChange={(e) => setAddress(e.target.value)} />
      <button onClick={handleSearch}>搜索</button>
      {location && (
        <div>
          经度:{location.lng},纬度:{location.lat}
        </div>
      )}
    </div>
  );
};

export default AddressInput;

handleSearch 函数中,我们先创建一个 AMap.Geocoder 实例,并指定城市为全国(因为有些地址不包含城市信息)。然后调用 getLocation 方法,传入要查询的地址和回调函数。回调函数中会返回查询结果,如果查询成功,则从返回结果中获取第一个地址的经纬度信息,并保存到组件状态中。最后,如果有经纬度信息,则在页面上显示出来。

需要注意的是,在 handleSearch 函数中,我们使用了 window.AMap,这是因为高德地图的 JavaScript API 是通过全局变量暴露出来的。如果你使用的是 TypeScript,需要在 tsconfig.json 中将 window 添加到全局变量中:

{
  "compilerOptions": {
    "lib": ["es6", "dom"],
    "types": ["node"],
    "target": "es5"
  },
  "globals": {
    "window": true
  }
}
React 实现高德地图地址逆编码功能:将地址转换为经纬度

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

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