欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

使用 react 实现按经纬度获取地址(地理/反地理编码)

最编程 2024-03-02 07:43:47
...
import React, { useState, useEffect } from 'react'; import axios from 'axios'; const AddAddress = () => { // 坐标 const [position, setPosition] = useState(null); // 位置 const [address, setAddress] = useState(""); useEffect(() => { if (navigator.geolocation) { // 通过浏览器获取位置 navigator.geolocation.getCurrentPosition(setPosition); } else { // 此浏览器不支持地理位置 console.log("Geolocation is not supported by this browser."); } }, []); const handleClick =async () => { // 根据坐标获取地址 const wz =await axios.get( 'https://restapi.amap.com/v3/geocode/regeo?key=你的key&location='+position.coords.longitude+','+position.coords.latitude ); console.log(wz.data); setAddress(wz.data.regeocode.formatted_address); }; return ( <div> {position ? ( <> <p>当前位置:</p> <p>{position.coords.latitude}, {position.coords.longitude}</p> </> ) : ( <p>正在获取当前位置...</p> )} <div className='sp'> <button onClick={()=>handleClick()}>获取定位</button> {address ? ( <> <p>当前位置:</p> <p>{address}</p> </> ) : ( <p>正在获取当前位置...</p> )} </div> </div> ); }; export default AddAddress;