import React, {createContext, useState, useEffect} from 'react'; import Geolocation from 'react-native-geolocation-service'; import {Platform, PermissionsAndroid, Alert} from 'react-native'; import {url} from '../url'; // import {accelerometer} from 'react-native-sensors'; import { setUpdateIntervalForType, SensorTypes, accelerometer, } from 'react-native-sensors'; import {latLng} from 'leaflet'; export const MapContext = createContext(); // //위치 정보 수집 권한 요청 async function requestPermission() { try { if (Platform.OS === 'ios') { return await Geolocation.requestAuthorization('always'); } if (Platform.OS === 'android') { return await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, ); } } catch (e) { console.log(e); } } export default function MapProvider({children}) { //현위치, marker 위치 검색내용 state const [location, setLocation] = useState(); const [searchQuery, setSearchQuery] = useState(null); const [isAccelerometerActive, setIsAccelerometerActive] = useState(false); // 상태 추가 //backedn 받아온 node const [startPoint, setStartPoint] = useState(); const [endPoint, setEndPoint] = useState({latitude: 0, longitude: 0}); const [nodes, setNodes] = useState([]); // 거리 환산 const [km, setKm] = useState(); //id임의값 let id = 1; const potholeReport = () => { fetch(`${url}/action/pothole_report`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ report_id: id, pothole_id: id, pothole_x: location.latitude, pothole_y: location.longitude, }), }) .then(response => response.json()) .then(data => { if (data.report === 'done') { id++; } }) .catch(err => { console.error(err); }); }; useEffect(() => { console.log(isAccelerometerActive); if (isAccelerometerActive) { // 1초에 한번 씩 업데이트 (default 100ms) setUpdateIntervalForType(SensorTypes.accelerometer, 1000); //임의 1초에 1번으로 변경 const subscription = accelerometer.subscribe(({z}) => { if (z >= 15) { console.log(z, ' z 축이 15g 이상입니다. Bump'); //임의 15, 원래30 테스트용 Alert.alert('알림', 'bump 발생'); potholeReport(); } }); return () => subscription.unsubscribe(); } }, [isAccelerometerActive]); //현위치 받아오기기 useEffect(() => { requestPermission().then(result => { if (result === 'granted') { // 구독 설정 const locationSubscription = Geolocation.watchPosition( position => { setLocation(position.coords); }, error => { console.log(error); }, { fastestInterval: 1000, }, ); // 구독 해제 함수를 반환하여 구독을 해제합니다. return () => { locationSubscription(); }; } }); }, [searchQuery]); useEffect(() => { if (location) { const speed = location.speed * 3.6; // km/hour로 계산 console.log('Current speed:' + speed + ' km/hour'); setIsAccelerometerActive(true); //현재 움직일 수 없으니 임의주석처리 // if (speed >= 8) { // console.log('8이상:' + speed + ' km/hour'); // setIsAccelerometerActive(true); // 속도가 8 이상일 때 가속도 센서 활성화 // } else { // setIsAccelerometerActive(false); // 속도가 8 미만일 때 가속도 센서 비활성화 // } } else { console.log('Location is not available yet.'); } }, [location]); //두좌표 거리 구하는 함수 function getDistance(lat1, lon1, lat2, lon2) { if (lat1 == lat2 && lon1 == lon2) return 0; var radLat1 = (Math.PI * lat1) / 180; var radLat2 = (Math.PI * lat2) / 180; var theta = lon1 - lon2; var radTheta = (Math.PI * theta) / 180; var dist = Math.sin(radLat1) * Math.sin(radLat2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.cos(radTheta); if (dist > 1) dist = 1; dist = Math.acos(dist); dist = (dist * 180) / Math.PI; dist = dist * 60 * 1.1515 * 1.609344 * 1000; if (dist < 100) dist = Math.round(dist / 10) * 10; else dist = Math.round(dist / 100) * 100; return dist; } //목적지 send const onQuery = query => { setSearchQuery(query); const {latitude, longitude} = location; return fetch(`${url}/trip/trip2`, { method: 'POST', headers: { 'Content-Type': 'application/json; charset=UTF-8', }, body: JSON.stringify({ dest1_x: latitude, dest1_y: longitude, path_end: query, }), }) .then(response => response.json()) .then(data => { const nodes = data.nodes; const start_point = data.start_point; const end_point = data.end_point; //end_point obj 변환 let endPointObj = {}; endPointObj.latitude = end_point[0]; endPointObj.longitude = end_point[1]; setEndPoint(endPointObj); //nodes obj 변환 let nodesArr = nodes; let resultNodes = nodesArr.map(i => { let nodesObj = {}; nodesObj.latitude = i[0]; nodesObj.longitude = i[1]; return nodesObj; }); setNodes(resultNodes); //start_point obj 변환 let startPointObj = {}; startPointObj.latitude = start_point[0]; startPointObj.longitude = start_point[1]; setStartPoint(startPointObj); // console.log('resultNodes', resultNodes); //nodes total km let total = []; for (let i = 0; i < resultNodes.length - 1; i++) { let km = getDistance( resultNodes[i].latitude, resultNodes[i].longitude, resultNodes[i + 1].latitude, resultNodes[i + 1].longitude, ); total.push(km); } const totalKm = total.reduce((acc, curr) => acc + curr, 0); const resultKm = totalKm / 1000; setKm(resultKm); return resultNodes; }); }; const value = React.useMemo(() => ({ onQuery, location, searchQuery, setSearchQuery, startPoint, endPoint, nodes, setNodes, km, })); return {children}; }