如何在 ReactJS 中使用地理位置 API

2025-06-08

如何在 ReactJS 中使用地理位置 API

地理定位用于查找网络设备的当前位置。它可用于 Google 地图、Uber、Tripadvisor 等应用程序。

在 ReactJS 中,我们可以使用 JavaScript 地理位置 API 查找用户当前的地理位置。

注意:少数可运行 HTML 5 的浏览器支持地理定位 API,例如 Google Chrome、Opera、Edge 等。

现在我们将了解使用地理位置 API 并查找用户的经纬度坐标所需遵循的步骤。

  • 首先,我们需要导入 React 以及此实现所需的库。我们将使用 React 的 useState 钩子来管理存储用户地理位置的变量。我们将在程序开头添加以下代码行来包含这些库和方法。
import React, { useState } from 'react';
Enter fullscreen mode Exit fullscreen mode
  • 我们将为 React 项目声明一个名为 App() 的组件函数,它将加载应用程序页面。我们将在其中封装所有地理位置方法。

  • 我们将为 React 项目声明一个名为 App() 的组件函数,它将加载应用程序页面。我们将在其中封装所有地理位置方法。

const [userLocation, setUserLocation] = useState(null);
Enter fullscreen mode Exit fullscreen mode
  • 下一步是定义一个函数来查找用户的地理位置并相应地更新 userLocation 变量。我们将使用下面显示的箭头函数。
const getUserLocation = () => { /*insert code here*/ };
Enter fullscreen mode Exit fullscreen mode
  • 在这个 getUserLocation 函数中,我们将添加所有用于查找用户地理位置的方法。首先,我们将检查用户浏览器是否支持地理位置功能。我们将使用一个简单的 if else 语句来封装 navigator.geolocation 函数。
if (navigator.geolocation) {
    // what to do if supported
}
else {
    // display an error if not supported
    console.error('Geolocation is not supported by this browser.');
}
Enter fullscreen mode Exit fullscreen mode
  • 现在,我们需要研究如果用户浏览器支持 navigator.geolocation 方法该怎么办。我们需要检索用户的位置。为此,我们使用 navigator.geolocation.getCurrentPosition() 函数。
navigator.geolocation.getCurrentPosition(
    (position) => {
        // what to do once we have the position
    },
    (error) => {
        // display an error if we cant get the users position
        console.error('Error getting user location:', error);
    }
);
Enter fullscreen mode Exit fullscreen mode
  • 一旦我们获得了用户的位置,我们就可以用它来查找用户的坐标和其他相关数据。要访问位置变量中包含的坐标,我们可以使用 poisiton.coords 方法。现在我们将创建两个变量来存储这些坐标以供以后使用。
const { latitude, longitude } = position.coords;
Enter fullscreen mode Exit fullscreen mode
  • 一旦我们获得用户的坐标,我们现在将通过调用 setUserLocation() 函数来更新我们的 userLocation 变量。
setUserLocation({ latitude, longitude });
Enter fullscreen mode Exit fullscreen mode
  • 现在我们已经存储了用户的位置坐标,下一步就是渲染一个 HTML 代码,将用户的坐标反映到网页上。为此,我们将添加一个按钮,当用户点击该按钮时,我们将调用 getUserLocation 函数并更新 userLocation 变量。
<button onClick={getUserLocation}>Get User Location</button>
Enter fullscreen mode Exit fullscreen mode
  • 如果成功检索到用户位置,我们还必须显示它。为此,我们将使用 && 语句以及 userLocation 变量,该变量包含用于打印用户坐标的所有 HTML 代码。一旦 userLocation 变量更新,它就不再是空值,并且该语句现在为 true;因此它会显示坐标。
{userLocation && (
    <div>
        <h2>User Location</h2>
        <p>Latitude: {userLocation.latitude}</p>
        <p>Longitude: {userLocation.longitude}</p>
    </div>
)}
Enter fullscreen mode Exit fullscreen mode

现在我们已经完成了检索用户地理位置所需遵循的所有步骤,现在我们将把所有步骤合并到一个文件中。

完整源代码

// import the required react libraries
import React, { useState } from 'react';

function App() {
  // const variable array to save the users location
  const [userLocation, setUserLocation] = useState(null);

  // define the function that finds the users geolocation
  const getUserLocation = () => {
    // if geolocation is supported by the users browser
    if (navigator.geolocation) {
      // get the current users location
      navigator.geolocation.getCurrentPosition(
        (position) => {
          // save the geolocation coordinates in two variables
          const { latitude, longitude } = position.coords;
          // update the value of userlocation variable
          setUserLocation({ latitude, longitude });
        },
        // if there was an error getting the users location
        (error) => {
          console.error('Error getting user location:', error);
        }
      );
    }
    // if geolocation is not supported by the users browser
    else {
      console.error('Geolocation is not supported by this browser.');
    }
  };

  // return an HTML page for the user to check their location
  return (
    <div>
      <h1>Geolocation App</h1>
      {/* create a button that is mapped to the function which retrieves the users location */}
      <button onClick={getUserLocation}>Get User Location</button>
      {/* if the user location variable has a value, print the users location */}
      {userLocation && (
        <div>
          <h2>User Location</h2>
          <p>Latitude: {userLocation.latitude}</p>
          <p>Longitude: {userLocation.longitude}</p>
        </div>
      )}
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

如果你想使用 TypeScript,源代码在这里

"use client"

import React, { useState } from "react";

export default function TestGeolocation() {
  const [userLocation, setUserLocation] = useState<{
    latitude: number;
    longitude: number;
  } | null>(null);

  const getUserLocation = () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const { latitude, longitude } = position.coords;

          setUserLocation({ latitude, longitude });
        },

        (error) => {
          console.error("Error get user location: ", error);
        }
      );
    } else {
      console.log("Geolocation is not supported by this browser");
    } 
  };

  return (
    <>
      <h1>Geolocation App</h1>
      {/* create a button that is mapped to the function which retrieves the users location */}
      <button onClick={getUserLocation}>Get User Location</button>
      {/* if the user location variable has a value, print the users location */}
      {userLocation && (
        <div>
          <h2>User Location</h2>
          <p>Latitude: {userLocation.latitude}</p>
          <p>Longitude: {userLocation.longitude}</p>
        </div>
      )}
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode
鏂囩珷鏉ユ簮锛�https://dev.to/choiruladamm/how-to-use-geolocation-api-using-reactjs-ndk
PREV
DEV 评论和帖子的格式化代码
NEXT
自然 CSS 艺术:前端挑战赛:六月版