Browse Source

Switching from context API to custom hook useLocation. Almost fixed bug in map focus.

master
GabrielTrettel 3 years ago
parent
commit
e3123c85e3
  1. 5
      src/app/components/map/LeafLetMap.js
  2. 21
      src/app/components/map/Map.html
  3. 7
      src/app/components/map/OpenStreetMap.js
  4. 4
      src/app/hooks/useLocation.js
  5. 51
      src/app/screens/MapFormScreen.js

5
src/app/components/map/LeafLetMap.js

@ -21,10 +21,9 @@ const loadHTMLFile = async () => {
return loadLocalAsset(HTML_FILE_PATH); return loadLocalAsset(HTML_FILE_PATH);
}; };
function goToRegion(mapRef, { lat, long, zoom }) {
function goToRegion(mapRef, position) {
mapRef.injectJavaScript(` mapRef.injectJavaScript(`
map.setView([${lat}, ${long}], ${zoom});`);
setCustomView(${position.lat}, ${position.long}, 16.5);`);
} }
const code_to_function = { const code_to_function = {

21
src/app/components/map/Map.html

@ -1,6 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<title>Mobile tutorial - Leaflet</title> <title>Mobile tutorial - Leaflet</title>
<meta charset="utf-8" /> <meta charset="utf-8" />
@ -11,12 +10,17 @@
<!-- type="image/x-icon" --> <!-- type="image/x-icon" -->
<!-- href="docs/images/favicon.ico" --> <!-- href="docs/images/favicon.ico" -->
<!-- /> --> <!-- /> -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
<link
rel="stylesheet"
href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossorigin="" />
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
crossorigin=""
/>
<script
src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
crossorigin=""></script>
crossorigin=""
></script>
<style> <style>
html, html,
body { body {
@ -45,9 +49,13 @@
<body> <body>
<div id="map"></div> <div id="map"></div>
<script> <script>
var map = L.map("map").setView([-23.533773, -46.625290], 5);
var map = L.map("map").setView([-23.533773, -46.62529], 5);
var markers = {}; var markers = {};
function setCustomView(lat, long, zoom) {
map.setView([lat, long], zoom);
}
L.tileLayer( L.tileLayer(
"https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoiZ2FicmllbC10cmV0dGVsIiwiYSI6ImNrb2RjNWIzYjAwczIyd25yNnUweDNveTkifQ.xRASmGTYm0ieS-FjVrXSjA", "https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoiZ2FicmllbC10cmV0dGVsIiwiYSI6ImNrb2RjNWIzYjAwczIyd25yNnUweDNveTkifQ.xRASmGTYm0ieS-FjVrXSjA",
{ {
@ -101,5 +109,4 @@
map.on("click", onMapClick); map.on("click", onMapClick);
</script> </script>
</body> </body>
</html> </html>

7
src/app/components/map/OpenStreetMap.js

@ -1,4 +1,4 @@
import React, { useState } from "react";
import React, { useState, useEffect } from "react";
import { View, StyleSheet, Text } from "react-native"; import { View, StyleSheet, Text } from "react-native";
import WebView from "react-native-webview"; import WebView from "react-native-webview";
import { import {
@ -44,9 +44,12 @@ export default function OpenStreetMap({
const [webviewContent, setWebviewContent] = useState(null); const [webviewContent, setWebviewContent] = useState(null);
const [markerListener, setMarkerListener] = useState(null); const [markerListener, setMarkerListener] = useState(null);
useEffect(() => {
if (mapRef != null) { if (mapRef != null) {
animateToPosition != null && goToRegion(mapRef, animateToPosition);
goToRegion(mapRef, animateToPosition);
} }
}, [mapRef, animateToPosition]);
markersList && markersList &&
mapRef && mapRef &&
notEmpy(markersList) && notEmpy(markersList) &&

4
src/app/hooks/useLocation.js

@ -1,4 +1,4 @@
import { useContext, useEffect, useState } from "react";
import { useEffect, useState } from "react";
import * as Location from "expo-location"; import * as Location from "expo-location";
export default function useLocation( export default function useLocation(
@ -18,7 +18,7 @@ export default function useLocation(
accuracy: Location.Accuracy.BestForNavigation, accuracy: Location.Accuracy.BestForNavigation,
}); });
setLocation({ latitude, longitude });
setLocation({ lat: latitude, long: longitude, zoom: 16.5 });
} catch (error) { } catch (error) {
console.log(error); console.log(error);
} }

51
src/app/screens/MapFormScreen.js

@ -1,29 +1,19 @@
import React, { useContext, useState, useEffect, memo } from "react"; import React, { useContext, useState, useEffect, memo } from "react";
import { StyleSheet, View, Text, Image } from "react-native"; import { StyleSheet, View, Text, Image } from "react-native";
import * as Location from "expo-location";
import colors from "../config/colors"; import colors from "../config/colors";
import * as Location from "expo-location";
import { EventLocationContext } from "../context/EventLocationContext"; import { EventLocationContext } from "../context/EventLocationContext";
import { TouchableOpacity } from "react-native-gesture-handler"; import { TouchableOpacity } from "react-native-gesture-handler";
import OpenStreetMap from "../components/map/OpenStreetMap"; import OpenStreetMap from "../components/map/OpenStreetMap";
import useLocation from "../hooks/useLocation";
// NOTE: Implementação posterior: É interessante adcionar um searchBox para que o usuário busque um endereço (google places autocomplete é uma api paga) // NOTE: 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 context = useContext(EventLocationContext); //local do evento const context = useContext(EventLocationContext); //local do evento
const [position, setPosition] = useState(null);
const location = useContext(EventLocationContext).eventCoordinates;
useEffect(() => {
setPosition({
lat: location["latitude"],
long: location["longitude"],
zoom: 16.5,
});
}, [location]);
const position = useLocation({ lat: 0.0, long: 0.0, zoom: 16.5 });
const [moveEndListener, setMoveEndListener] = useState(null); const [moveEndListener, setMoveEndListener] = useState(null);
console.log("=====POSIÇÃO: " + typeof location);
const getAddress = async (coordenadas) => { const getAddress = async (coordenadas) => {
Location.setGoogleApiKey("AIzaSyD_wuuokS3SVczc8qSASrsBq0E5qIpdyMc"); Location.setGoogleApiKey("AIzaSyD_wuuokS3SVczc8qSASrsBq0E5qIpdyMc");
@ -32,9 +22,10 @@ const MapFormScreen = (props) => {
console.log(address); console.log(address);
console.log(coordenadas); console.log(coordenadas);
if (address[0] != undefined) { if (address[0] != undefined) {
var street = (address[0].street == null ? "" : address[0].street);
var number = (address[0].name == null ? "" : ", " + address[0].name);
var district = (address[0].district == null ? "" : "\n" + address[0].district);
var street = address[0].street == null ? "" : address[0].street;
var number = address[0].name == null ? "" : ", " + address[0].name;
var district =
address[0].district == null ? "" : "\n" + address[0].district;
context.saveNewLocation(street + number + district, coordenadas); context.saveNewLocation(street + number + district, coordenadas);
} else { } else {
//Quando o usuário não da permissão de acesso da localização o geoCode retorna um array vazio //Quando o usuário não da permissão de acesso da localização o geoCode retorna um array vazio
@ -48,15 +39,19 @@ const MapFormScreen = (props) => {
//leva o mapa pra localização escolhida pelo usuário //leva o mapa pra localização escolhida pelo usuário
const moveLocation = (l) => { const moveLocation = (l) => {
console.log(l);
setMoveEndListener(l); setMoveEndListener(l);
setPosition(l);
// setPosition({
// lat: l["latitude"],
// long: l["longitude"],
// zoom: 16.5,
// });
}; };
return ( return (
<View style={styles.container}> <View style={styles.container}>
<OpenStreetMap <OpenStreetMap
style={styles.mapStyle}
moveEndListener={e => moveLocation(e)}
moveEndListener={(e) => moveLocation(e)}
animateToPosition={position} animateToPosition={position}
/> />
<View style={styles.markerFixed}> <View style={styles.markerFixed}>
@ -89,15 +84,7 @@ const styles = StyleSheet.create({
backgroundColor: colors.black, backgroundColor: colors.black,
flex: 1, flex: 1,
justifyContent: "center", justifyContent: "center",
flexDirection: "row"
},
mapStyle: {
position: "absolute",
alignSelf: "center",
top: 0,
left: 0,
right: 0,
bottom: 0,
flexDirection: "row",
}, },
button: { button: {
backgroundColor: "#1976D2", backgroundColor: "#1976D2",
@ -128,14 +115,6 @@ const styles = StyleSheet.create({
height: "50%", height: "50%",
width: 40, width: 40,
}, },
callback: {
bottom: 100,
alignSelf: "center",
alignItems: "center",
backgroundColor: "gray",
width: "80%",
padding: 10,
},
}); });
export default MapFormScreen; export default MapFormScreen;
Loading…
Cancel
Save