[React-Native] WebView를 사용하여 웹 콘텐츠에 GPS 위치 전달

2023. 11. 8. 13:45React Native

React Native에서 WebView를 사용하여 웹 콘텐츠에 GPS 위치를 제공하고자 할 때

다음과 같은 단계를 거쳐 구현할 수 있습니다.

권한 요청

모바일 애플리케이션에서 GPS 위치 정보에 접근하려면 사용자로부터 위치 정보 접근에 대한 권한을 얻어야 합니다. React Native에서는 react-native-permissions 라이브러리를 통해 이를 수행할 수 있습니다.

import { PermissionsAndroid } from 'react-native';
import { request, PERMISSIONS } from 'react-native-permissions';

async function requestLocationPermission() {
  try {
    const granted = await request(PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION);
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log('You can use the location');
    } else {
      console.log('Location permission denied');
    }
  } catch (err) {
    console.warn(err);
  }
}

iOS에서는 Info.plist에 위치 서비스에 대한 권한 요청을 추가해야 합니다.

위치 정보 얻기

권한을 얻었다면, navigator.geolocation API를 사용해 현재 위치를 얻을 수 있습니다.

function getLocation() {
  return new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(
      position => {
        resolve(position);
      },
      error => reject(error),
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
    );
  });
}

WebView와 통신

위치 정보를 웹 콘텐츠로 전달하려면 postMessage 메소드를 사용합니다. 이를 위해 WebView의 ref를 사용하여 injectJavaScript 함수를 호출합니다.

<WebView
  ref={ref => {
    this.webview = ref;
  }}
  source={{ uri: 'https://example.com' }}
  onMessage={this.handleMessage}
/>

사용자가 위치 정보 요청 버튼을 웹 페이지에서 클릭하면, 해당 이벤트를 감지하고 React Native로 메시지를 전송합니다. 그리고 React Native에서는 이 메시지를 받아 위치 정보를 요청하고 결과를 웹 콘텐츠로 다시 전송합니다.

위치 정보를 웹 콘텐츠로 전송

React Native에서 위치 정보를 받은 후, 웹 콘텐츠에 해당 정보를 전송합니다. 이 때 injectJavaScript 함수를 사용합니다.

// 위치 정보를 얻은 후 웹뷰로 전송하는 함수
async function sendLocationToWeb() {
  try {
    const position = await getLocation();
    const script = `
      window.postMessage(${JSON.stringify({
        type: 'location',
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
      })}, '*');
    `;
    this.webview.injectJavaScript(script);
  } catch (error) {
    console.error(error);
  }
}

웹 페이지에서는 window.addEventListener('message', handleMessage)를 통해 메시지를 받을 수 있습니다.

window.addEventListener('message', event => {
  const data = JSON.parse(event.data);
  if (data.type === 'location') {
    console.log('Latitude:', data.latitude, 'Longitude:', data.longitude);
    // 위치 정보를 웹 페이지에서 사용
  }
});