reactnative获取经纬度 获取此地信息 @react-native-community/geolocation

Reactnative 获取位置

javascript 复制代码
import Geolocation from '@react-native-community/geolocation';
javascript 复制代码
  const [coords, setCoords] = useState(null); // 存储经纬度
  const [addressLoading, setAddressLoading] = useState(false);


  const getLocation = () => {
    setAddressLoading(true);
    Geolocation.getCurrentPosition(
      async (position) => {
        console.log(position);
        console.log(position.coords);
        const { latitude, longitude } = position.coords;

        setCoords({ latitude, longitude });
        // 调用逆地理编码
        await getAddressFromCoords(latitude, longitude);
      },
      (error) => {
        console.log(error.code, error.message);
      },
      { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
    );
  }
  // 2. 逆地理编码:经纬度转具体地址
  const getAddressFromCoords = async (latitude, longitude) => {
    try {
      // 高德逆地理编码 API 接口
      const url = `https://restapi.amap.com/v3/geocode/regeo?output=json&location=${longitude},${latitude}&key=${AMAP_API_KEY}`;

      const response = await fetch(url);
      const result = await response.json();

      if (result.status === '1') {
        // 解析核心地址信息
        const regeocode = result.regeocode;
        const addressComponent = regeocode.addressComponent; // 地址组件(省/市/区/街道)
        // const formattedAddress = regeocode.formatted_address; // 完整地址(如:浙江省杭州市西湖区文三路XX号)
        // const neighborhood = addressComponent.neighborhood || {}; // 小区/社区
        // const building = addressComponent.building || {}; // 楼栋




        // 拼接更精准的地址(按需调整)
        let detailedAddress = addressComponent.province + addressComponent.city + addressComponent.district;
        // if (formattedAddress) detailedAddress += formattedAddress;
        // if (neighborhood.name) detailedAddress += ` ${neighborhood.name}`;
        // if (building.name) detailedAddress += ` ${building.name}`;

        setAddress(detailedAddress || '暂无位置');
        setAddressLoading(false);
      } else {
        setAddress(`暂无位置`);
        setAddressLoading(false);

      }
    } catch (err) {
      setAddress('暂无位置');
      setAddressLoading(false);

      console.error('逆地理编码失败:', err);
    }
  };
javascript 复制代码
     {/* 定位 */}
            <TouchableOpacity style={[styles.row, { borderBottomWidth: 0 }]}
              onPress={() => {
                getLocation()
              }}

            >
              <View style={styles.rowLeft}>
                <Image
                  source={require('@/images/gajyIcon/setting-location.png')}
                  resizeMode="contain"
                  style={styles.icon}
                />
                <Text style={styles.label}>定位</Text>
              </View>
              <View style={styles.rowRight}>
                {/* <Text>{address}</Text> */}
                <View style={styles.rowRight}>

                  {addressLoading ? (
                    // ActivityIndicator 是 React Native 内置的加载转圈组件
                    <ActivityIndicator
                      size="small"  // 可选:small / large
                      color="#0066ff"  // 自定义加载圈颜色
                      style={styles.loading}  // 加载组件的样式
                    />
                  ) : (
                    <Text>{address}</Text>
                  )}
                </View>
                {/* <Image
                  source={require('@/images/gajyIcon/rightArr.png')}
                  resizeMode="contain"
                  style={styles.arrow}
                /> */}
              </View>
            </TouchableOpacity>
相关推荐
三十而立洋1 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
卡布鲁1 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
李少兄1 天前
JavaScript 隐式全局变量解析
javascript
沙蒿同学1 天前
我用 Go 搭了一条 AI Agent 流水线:从 1 张商品图到一整套淘宝详情页
前端·javascript·后端
paopaokaka_luck1 天前
智慧社区综合服务小程序(人脸识别、AI问答、Echarts图形化分析)
前端·javascript·spring boot·spring·数据分析·echarts
Hilaku1 天前
为什么死磕 1px 的团队,用户体验反而更差?
前端·javascript·程序员
陈拉斯1 天前
给公司年会写了个大屏抽奖系统:动画在前端跑,凭什么说结果没被改?
javascript
yzy851 天前
Vue中下载或打开文件的JavaScript方法
前端·javascript·vue
用户298698530141 天前
在 React 中用 JavaScript 将 Word 转换为文本
前端·javascript·react.js
李少兄1 天前
深入解析 JavaScript 中的 `document` 对象
javascript