unioil-loyalty-rn-app/app/screens/iqair/map/Map/index.js

128 lines
3.2 KiB
JavaScript

import React, { useEffect, useState, useRef } from 'react';
import {
View,
StyleSheet,
AppState
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import IQAIRDetails from './IQAIRDetails';
import CustomHeader from '../../../../components/header.js';
import RNLocation from 'react-native-location';
import REQUEST from '../../../../components/api';
import DB from '../../../../components/storage';
import Map from './Map';
const MapContainer = () => {
const navigation = useNavigation();
const [permissionLocation, setPermissionLocation] = useState(false);
const [selected, setSelected] = useState(undefined);
const [stations, setStations] = useState([]);
const [region, setRegion] = useState({
latitude: 14.599512,
longitude: 120.984222,
latitudeDelta: 15,
longitudeDelta: 11,
})
const mapRef = useRef(null);
const appState = useRef(AppState.currentState);
useEffect(() => {
AppState.addEventListener('change', handleAppStateChange);
handleAppStateChange();
}, [])
const handleAppStateChange = (nextAppState) => {
if(!nextAppState || (appState.current?.match(/inactive|background/) && nextAppState === 'active')) {
getPermissionStatus();
}
appState.current = nextAppState;
}
const getPermissionStatus = () => {
RNLocation.requestPermission({
ios: "whenInUse", // or 'always'
}).then(granted => {
if(granted) {
setPermissionLocation(true);
init()
} else {
setPermissionLocation(false);
Alert.alert("Error", "Location GPS is disabled.")
}
})
}
const init = async () => {
RNLocation.getLatestLocation({ timeout: 20000 }).then(latestLocation => {
const coords = {longitude: latestLocation.longitude, latitude: latestLocation.latitude};
fetch(coords);
goToRegion(coords);
})
}
const goToRegion = (data) => {
if(!data) return
let initialRegion = {
latitude: parseFloat(data.latitude),
longitude: parseFloat(data.longitude),
latitudeDelta: 0.0922,
longitudeDelta: 0.0421
}
setRegion(initialRegion);
}
const fetch = async (location) => {
if(!location) return false
let SESSION = await DB.session()
REQUEST('gas_stations', 'post', {
Authorization: SESSION.token
}, {}, {
lcard_uuid: SESSION.user.lcard_uuid,
longitude: location.longitude,
latitude: location.latitude
}, async (res) => {
setStations(res.data);
}, (error) => {
console.log(error);
})
}
const getRef = (ref) => {
mapRef.current = ref;
}
const onMarkerPressed = (e) => {
goToRegion(e.nativeEvent.coordinate);
setSelected(e.nativeEvent.coordinate);
}
const onMapReady = () => {}
return (
<View style={styles.container}>
<CustomHeader back={true} onBackPress={() => navigation.goBack()} title="IQAIR Location" menu={false} navigation={navigation} />
<Map
region={region}
getRef={getRef}
onMapReady={onMapReady}
markers={stations}
onMarkerPressed={onMarkerPressed}
/>
<IQAIRDetails
selected={selected}
/>
</View>
)
}
export default MapContainer
const styles = StyleSheet.create({
container: {
flex: 1
}
})