Browse Source

creating a context to get user location

master
analuizaff 4 years ago
parent
commit
a700a72060
  1. 15
      src/App.js
  2. 3
      src/app/components/EventLocationInput.js
  3. 4
      src/app/config/globals.js
  4. 67
      src/app/context/CurrentLocationContext.js
  5. 29
      src/app/context/EventLocationContext.js
  6. 4
      src/app/hooks/useLocation.js
  7. 25
      src/app/screens/MapFeedScreen.js
  8. 25
      src/app/screens/MapFormScreen.js
  9. 2
      src/app/screens/RiverFloodSharingDataScreen.js
  10. 6
      src/app/screens/SharingDataScreen.js
  11. 2
      src/app/screens/SharingFloodZonesScreen.js

15
src/App.js

@ -10,6 +10,7 @@ import FlashMessage from "react-native-flash-message";
import { createStackNavigator } from '@react-navigation/stack'; import { createStackNavigator } from '@react-navigation/stack';
import AppNavigator from "./app/navigation/AppNavigator"; import AppNavigator from "./app/navigation/AppNavigator";
import EventLocationProvider from "./app/context/EventLocationContext"; import EventLocationProvider from "./app/context/EventLocationContext";
import CurrentLocationProvider from "./app/context/CurrentLocationContext";
export default function App() { export default function App() {
global.userDataBase = openDatabase(); global.userDataBase = openDatabase();
@ -17,11 +18,13 @@ export default function App() {
const Stack = createStackNavigator(); const Stack = createStackNavigator();
return ( return (
<EventLocationProvider>
<NavigationContainer theme={navigationTheme}>
<AppNavigator />
<FlashMessage position="top" />
</NavigationContainer>
</EventLocationProvider>
<CurrentLocationProvider>
<EventLocationProvider>
<NavigationContainer theme={navigationTheme}>
<AppNavigator />
<FlashMessage position="top" />
</NavigationContainer>
</EventLocationProvider>
</CurrentLocationProvider>
); );
} }

3
src/app/components/EventLocationInput.js

@ -5,9 +5,6 @@ import { Text } from "react-native";
const EventLocationInput = () => { const EventLocationInput = () => {
const context = useContext(EventLocationContext); const context = useContext(EventLocationContext);
console.log("CONTEXTO: " + context.eventLocation);
const data = context.eventLocation;
return( return(
<Text> {context.eventLocation} </Text> <Text> {context.eventLocation} </Text>

4
src/app/config/globals.js

@ -2,5 +2,5 @@
global.userDataBase = undefined; global.userDataBase = undefined;
//Endereço do evento //Endereço do evento
global.eventAddress = " ";
global.eventCoordinates = undefined;
//global.eventAddress = " ";
//global.eventCoordinates = undefined;

67
src/app/context/CurrentLocationContext.js

@ -0,0 +1,67 @@
import React, { useState, createContext, useEffect } from "react"
import * as Location from "expo-location";
export const CurrentLocationContext = createContext();
const CurrentLocationProvider = ({ children }) => {
const [currentLocation, setCurrentLocation] = useState("endereço usuário");
const [currentCoordinates, setCurrentCoordinates] = useState({ longitude: 0.0, latitude: 0.0 });
//get user current location coordinates
const getCoordinates = async () => {
try {
const { granted } = await Location.requestPermissionsAsync();
if (!granted) return;
const {
coords: { latitude, longitude },
} = await Location.getCurrentPositionAsync({
accuracy: Location.Accuracy.Highest,
});
setCurrentCoordinates({ latitude, longitude });
//console.log({ latitude, longitude });
// console.log(currentCoordinates);
getAddress({ latitude, longitude });
} catch (error) {
console.log(error);
}
};
//get user current location address
const getAddress = async (coordenadas) => {
// console.log("PEGANDO ENDEREÇO");
Location.setGoogleApiKey("AIzaSyD_wuuokS3SVczc8qSASrsBq0E5qIpdyMc");
const address = await Location.reverseGeocodeAsync(coordenadas);
setCurrentLocation(address[0].street + ", " + address[0].name + "\n" + address[0].district, coordenadas.x);
//console.log(currentLocation);
};
useEffect(() => {
getCoordinates();
//console.log(currentCoordinates.latitude);
}, []);
const getCurrentLocation = (coordenadas) => {
setCurrentCoordinates(coordenadas);
}
return (
<CurrentLocationContext.Provider value={{
currentLocation,
currentCoordinates,
getCurrentLocation,
}}>
{children}
</CurrentLocationContext.Provider>
)
}
export default CurrentLocationProvider;

29
src/app/context/EventLocationContext.js

@ -1,19 +1,38 @@
import React, { useState, createContext } from "react"
import React, { useState, createContext, useContext, useEffect } from "react"
import { CurrentLocationContext } from "./CurrentLocationContext";
export const EventLocationContext = createContext(); export const EventLocationContext = createContext();
const EventLocationProvider = ({ children }) => { const EventLocationProvider = ({ children }) => {
const [eventLocation, setEventLocation] = useState("endereço");
const saveNewLocation = (local) => {
const context = useContext(CurrentLocationContext);
//problema: as vzs renderiza antes de carregar a localização correta do usuário
const [eventLocation, setEventLocation] = useState(context.currentLocation);
const [eventCoordinates, setEventCoordinates] = useState(context.currentCoordinates);
console.log(context.currentLocation);
//Função chamada em MapFormScreen após o usuário definir a nova localização
const saveNewLocation = (local, coordinates) => {
setEventLocation(local); setEventLocation(local);
console.log("NOVO LOCAL: " + local);
setEventCoordinates(coordinates);
// console.log("NOVO LOCAL: " + local);
// console.log("NOVa coordenada: " + coordinates.latitude);
}
const defaultLocation = () =>{
setEventCoordinates(context.currentCoordinates);
setEventLocation(context.currentLocation);
} }
return ( return (
<EventLocationContext.Provider value={{ <EventLocationContext.Provider value={{
eventLocation, eventLocation,
saveNewLocation
eventCoordinates,
saveNewLocation,
defaultLocation,
}}> }}>
{children} {children}
</EventLocationContext.Provider> </EventLocationContext.Provider>

4
src/app/hooks/useLocation.js

@ -1,4 +1,4 @@
import { useEffect, useState } from "react";
import { useContext, useEffect, useState } from "react";
import * as Location from "expo-location"; import * as Location from "expo-location";
export default function useLocation( export default function useLocation(
@ -15,7 +15,7 @@ export default function useLocation(
const { const {
coords: { latitude, longitude }, coords: { latitude, longitude },
} = await Location.getCurrentPositionAsync({ } = await Location.getCurrentPositionAsync({
accuracy: Location.Accuracy.Highest,
accuracy: Location.Accuracy.BestForNavigation,
}); });
setLocation({ latitude, longitude }); setLocation({ latitude, longitude });

25
src/app/screens/MapFeedScreen.js

@ -1,34 +1,21 @@
import React, { useEffect, useState } from "react";
import React, { useContext, useEffect, useState } from "react";
import { StyleSheet, View } from "react-native"; import { StyleSheet, View } from "react-native";
import MapView from "react-native-maps"; import MapView from "react-native-maps";
import colors from "../config/colors"; import colors from "../config/colors";
import { screen_width, screen_height } from "../config/dimensions"; import { screen_width, screen_height } from "../config/dimensions";
import useLocation from "../hooks/useLocation";
import useMarkers from "../hooks/selectFromDB"; import useMarkers from "../hooks/selectFromDB";
import MapMarker from "../components/MapMarker"; import MapMarker from "../components/MapMarker";
import attachFocusToQuery from "../hooks/useFocus"; import attachFocusToQuery from "../hooks/useFocus";
import * as Location from 'expo-location';
//1/3: tirar essa função daqui depois - poderia ser um componente
async function getAddress(coordenadas) {
Location.setGoogleApiKey("AIzaSyD_wuuokS3SVczc8qSASrsBq0E5qIpdyMc");
global.eventAddress = await Location.reverseGeocodeAsync(coordenadas);
console.log(global.eventAddress);
global.eventCoordinates = coordenadas;
}
import { CurrentLocationContext } from "../context/CurrentLocationContext";
function MapFeedScreen(props) { function MapFeedScreen(props) {
const location = useLocation({
latitude: -22.1070263,
longitude: -51.3948396,
});
getAddress(location);
const context = useContext(CurrentLocationContext);
const location = context.currentCoordinates;
//const context = useContext(CurrentLocationContext)
const hasToQuery = attachFocusToQuery(); const hasToQuery = attachFocusToQuery();
const markers = useMarkers(hasToQuery); const markers = useMarkers(hasToQuery);

25
src/app/screens/MapFormScreen.js

@ -8,30 +8,24 @@ import { screen_width, screen_height } from "../config/dimensions";
import useLocation from "../hooks/useLocation"; import useLocation from "../hooks/useLocation";
import * as Location from 'expo-location'; import * as Location from 'expo-location';
import { EventLocationContext } from "../context/EventLocationContext"; import { EventLocationContext } from "../context/EventLocationContext";
// import SearchBox from "../components/maps/SearchBox";
//Implementação posterior: É interessante adcionar um searchBox para que o usuário busque um endereço (google places autocomplete é uma api paga)
var address;
//Implementação posterior: É interessante adcionar um searchBox para que o usuário busque um endereço (google places autocomplete é uma api paga)
const MapFormScreen = (props) => { const MapFormScreen = (props) => {
const location = useLocation({
latitude: -23.533773,
longitude: -46.625290,
});
// const location = useLocation({
// latitude: -23.533773,
// longitude: -46.625290,
//});
const getAddress = async(coordenadas) => { const getAddress = async(coordenadas) => {
Location.setGoogleApiKey("AIzaSyD_wuuokS3SVczc8qSASrsBq0E5qIpdyMc"); Location.setGoogleApiKey("AIzaSyD_wuuokS3SVczc8qSASrsBq0E5qIpdyMc");
address = await Location.reverseGeocodeAsync(coordenadas.x);
console.log(address);
// address[0].street+", " + address[0].name}
// {address[0].district}
global.eventCoordinates = coordenadas.x;
context.saveNewLocation(address[0].street+", " + address[0].name);
const address = await Location.reverseGeocodeAsync(coordenadas.x);
// console.log(address);
context.saveNewLocation(address[0].street+", " + address[0].name +"\n" + address[0].district, coordenadas.x);
} }
const context = useContext(EventLocationContext); const context = useContext(EventLocationContext);
//console.log(context.eventLocation);
// console.log(markers); // console.log(markers);
const map_scale = 0.003; const map_scale = 0.003;
@ -40,7 +34,8 @@ const MapFormScreen = (props) => {
longitudeDelta: map_scale * (screen_width / screen_height), longitudeDelta: map_scale * (screen_width / screen_height),
}; };
const local = useLocation();
//const local = useLocation();
//Deixei a localizção setada em sp só para fazer os testes
return ( return (
<View style={styles.container}> <View style={styles.container}>

2
src/app/screens/RiverFloodSharingDataScreen.js

@ -32,7 +32,7 @@ const borderWidth = 4;
function RiverFloodSharingDataScreen(props) { function RiverFloodSharingDataScreen(props) {
const [riverScale, setRiverScale] = useState(-1); const [riverScale, setRiverScale] = useState(-1);
const location = useLocation();
const location = "useLocation()";
const [error, setError] = useState(false); const [error, setError] = useState(false);
const [date, setDate] = useState(moment()); const [date, setDate] = useState(moment());

6
src/app/screens/SharingDataScreen.js

@ -1,17 +1,19 @@
import React from "react";
import React, { useContext, useEffect, useState } from "react";
import { StyleSheet, View } from "react-native"; import { StyleSheet, View } from "react-native";
import { Image, Text, TouchableOpacity, ScrollView } from "react-native"; import { Image, Text, TouchableOpacity, ScrollView } from "react-native";
import assets from "../config/assets"; import assets from "../config/assets";
import { scaleDimsFromWidth, dimensions } from "../config/dimensions"; import { scaleDimsFromWidth, dimensions } from "../config/dimensions";
import { Svg, Image as ImageSvg, SvgXml } from "react-native-svg"; import { Svg, Image as ImageSvg, SvgXml } from "react-native-svg";
import Pluviometer from "../assets/pluviometer-logo.svg";
//1/3 //1/3
function SharingDataScreen({ navigation }) { function SharingDataScreen({ navigation }) {
const dims = scaleDimsFromWidth(93, 106, 35); const dims = scaleDimsFromWidth(93, 106, 35);
// const dims = { width: "100%", height: "100%" }; // const dims = { width: "100%", height: "100%" };
return ( return (
<View style={styles.container}> <View style={styles.container}>
<ScrollView> <ScrollView>

2
src/app/screens/SharingFloodZonesScreen.js

@ -33,7 +33,7 @@ const validationSchema = Yup.object().shape({
function SharingFloodZonesScreen(props) { function SharingFloodZonesScreen(props) {
const [passable, setPassable] = useState(-1); const [passable, setPassable] = useState(-1);
const [error, setError] = useState(false); const [error, setError] = useState(false);
const location = useLocation();
const location = "useLocation()";
const [date, setDate] = useState(moment()); const [date, setDate] = useState(moment());
const [time, setTime] = useState(moment()); const [time, setTime] = useState(moment());

Loading…
Cancel
Save