React 简便获取经纬度

以下是关于React获取定位经纬度的代码解释:

复制代码
import React, { useEffect, useState } from 'react';

const LocationComponent = () => {
  const [latitude, setLatitude] = useState(null);
  const [longitude, setLongitude] = useState(null);

  useEffect(() => {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        setLatitude(position.coords.latitude);
        setLongitude(position.coords.longitude);
      },
      (error) => {
        console.error(error);
      }
    );
  }, []);

  return (
    <div>
      {latitude && longitude ? (
        <p>经度: {longitude}, 纬度: {latitude}</p>
      ) : (
        <p>正在获取位置信息...</p>
      )}
    </div>
  );
};

export default LocationComponent;
  • import React, { useEffect, useState } from 'react'; 导入React库中的React对象以及useEffect和useState钩子函数。

  • const LocationComponent = () => { ... } 创建一个名为LocationComponent的函数式组件。

  • const latitude, setLatitude = useState(null); 使用useState钩子函数创建一个名为latitude的状态变量,并设置初始值为null。setLatitude是用于更新latitude状态的函数。

  • const longitude, setLongitude = useState(null); 使用useState钩子函数创建一个名为longitude的状态变量,并设置初始值为null。setLongitude是用于更新longitude状态的函数。

  • useEffect(() => { ... }, \[\]); 使用useEffect钩子函数,在组件渲染时执行副作用代码。空数组作为第二个参数,表示只在组件挂载时执行一次。

  • navigator.geolocation.getCurrentPosition(...) 使用浏览器的Geolocation API获取当前位置信息。

  • (position) => { ... } 定义一个回调函数,当成功获取位置信息时被调用。position参数包含了经纬度等信息。

  • setLatitude(position.coords.latitude); 更新latitude状态变量为获取到的纬度值。

  • setLongitude(position.coords.longitude); 更新longitude状态变量为获取到的经度值。

  • (error) => { console.error(error); } 定义一个回调函数,当获取位置信息失败时被调用。error参数包含了错误信息。

  • {latitude && longitude ? ( ... ) : ( ... )} 使用条件渲染语法,如果latitude和longitude都有值,则渲染经纬度信息,否则渲染正在获取位置信息的提示。

  • 经度: {longitude}, 纬度: {latitude}

    显示经纬度信息。

  • 正在获取位置信息...

    显示正在获取位置信息的提示。

  • export default LocationComponent; 导出LocationComponent组件,使其可以在其他地方被引用和使用。

请注意,这段代码使用了React的函数式组件和Hooks特性,以及浏览器的Geolocation API来获取位置信息。

相关推荐
巴勒个啦13 分钟前
2026 年 CSS 选型真相:我用 Tailwind v4 + 原生新特性重构了一个组件库
前端·angular.js
LEE14 分钟前
别再堆 AGENTS.md 了:前端团队如何把 AI Coding 做成一套可执行的工程系统
前端·后端
三十而立洋21 分钟前
JavaScript 原型链:一张图讲透「对象继承」的底层真相
前端·javascript
工具派25 分钟前
markdown在线编辑器怎么选?渲染管线的3个坑和md转PDF跑版记录
前端·后端
平头哥技术团队26 分钟前
Day 13 | 调 line-height 和 margin:三处间距让名片页脱离模板感
开发语言·前端·javascript·学习·html5
一位正在转型AI全栈的前端工程师28 分钟前
AI 全栈学习之旅 -Week 9:什么是AI Agent?从Function Calling到LangGraph
前端·python
计算机魔术师1 小时前
Claude Opus 5 干不过人类客服?23.9% 的通过率撕开 Agent 真相
前端
cjy0001111 小时前
2026年9月零基础能听懂国内 FDE 讲师的课吗?
大数据·前端·人工智能·fde
南雨北斗1 小时前
wangeditor5 在vue3项目中的正确配置
前端
老三_Micheal1 小时前
一文搞懂 Axios 请求参数详解:headers、params 与 body 的区别和使用场景
javascript