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. 185
      src/app/components/map/Map.html
  3. 23
      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);
};
function goToRegion(mapRef, { lat, long, zoom }) {
function goToRegion(mapRef, position) {
mapRef.injectJavaScript(`
map.setView([${lat}, ${long}], ${zoom});`);
setCustomView(${position.lat}, ${position.long}, 16.5);`);
}
const code_to_function = {

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

@ -1,105 +1,112 @@
<!DOCTYPE html>
<html>
<head>
<title>Mobile tutorial - Leaflet</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<head>
<title>Mobile tutorial - Leaflet</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- <link -->
<!-- rel="shortcut icon" -->
<!-- type="image/x-icon" -->
<!-- href="docs/images/favicon.ico" -->
<!-- /> -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossorigin="" />
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
crossorigin=""></script>
<style>
html,
body {
height: 100%;
margin: 0;
}
<!-- <link -->
<!-- rel="shortcut icon" -->
<!-- type="image/x-icon" -->
<!-- href="docs/images/favicon.ico" -->
<!-- /> -->
<link
rel="stylesheet"
href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossorigin=""
/>
<script
src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
crossorigin=""
></script>
<style>
html,
body {
height: 100%;
margin: 0;
}
#map {
width: 600px;
height: 400px;
}
</style>
<style>
body {
padding: 0;
margin: 0;
}
#map {
width: 600px;
height: 400px;
}
</style>
<style>
body {
padding: 0;
margin: 0;
}
#map {
height: 100%;
width: 100vw;
}
</style>
</head>
#map {
height: 100%;
width: 100vw;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map = L.map("map").setView([-23.533773, -46.625290], 5);
var markers = {};
<body>
<div id="map"></div>
<script>
var map = L.map("map").setView([-23.533773, -46.62529], 5);
var markers = {};
L.tileLayer(
"https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoiZ2FicmllbC10cmV0dGVsIiwiYSI6ImNrb2RjNWIzYjAwczIyd25yNnUweDNveTkifQ.xRASmGTYm0ieS-FjVrXSjA",
{
maxZoom: 18,
attribution:
'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
id: "mapbox/streets-v11",
tileSize: 512,
zoomOffset: -1,
function setCustomView(lat, long, zoom) {
map.setView([lat, long], zoom);
}
).addTo(map);
var moveend = true;
L.tileLayer(
"https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoiZ2FicmllbC10cmV0dGVsIiwiYSI6ImNrb2RjNWIzYjAwczIyd25yNnUweDNveTkifQ.xRASmGTYm0ieS-FjVrXSjA",
{
maxZoom: 18,
attribution:
'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
id: "mapbox/streets-v11",
tileSize: 512,
zoomOffset: -1,
}
).addTo(map);
function onMapClick(e) {
var payload = {
code: 1,
content: {
latitude: e.latlng.lat.toString().slice(0, 8),
longitude: e.latlng.lng.toString().slice(0, 8),
},
};
window.ReactNativeWebView.postMessage(JSON.stringify(payload));
}
var moveend = true;
function onPopupClick(e) {
var payload = {
code: 2,
content: this.options.ID,
};
window.ReactNativeWebView.postMessage(JSON.stringify(payload));
}
function onMapClick(e) {
var payload = {
code: 1,
content: {
latitude: e.latlng.lat.toString().slice(0, 8),
longitude: e.latlng.lng.toString().slice(0, 8),
},
};
window.ReactNativeWebView.postMessage(JSON.stringify(payload));
}
//var marker = L.marker([0, 0]).bindPopup("Your pickup spot is in this area").addTo(map);
function onMoveEnd(e) {
//marker.setLatLng(map.getCenter());
function onPopupClick(e) {
var payload = {
code: 2,
content: this.options.ID,
};
window.ReactNativeWebView.postMessage(JSON.stringify(payload));
}
var payload = {
code: 3,
content: {
latitude: map.getCenter().lat,
longitude: map.getCenter().lng,
},
};
// map.setView([e.latlng.lat, e.latlng.lng]);
window.ReactNativeWebView.postMessage(JSON.stringify(payload));
}
//var marker = L.marker([0, 0]).bindPopup("Your pickup spot is in this area").addTo(map);
function onMoveEnd(e) {
//marker.setLatLng(map.getCenter());
map.on("moveend", onMoveEnd);
map.on("click", onMapClick);
</script>
</body>
var payload = {
code: 3,
content: {
latitude: map.getCenter().lat,
longitude: map.getCenter().lng,
},
};
// map.setView([e.latlng.lat, e.latlng.lng]);
window.ReactNativeWebView.postMessage(JSON.stringify(payload));
}
map.on("moveend", onMoveEnd);
map.on("click", onMapClick);
</script>
</body>
</html>

23
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 WebView from "react-native-webview";
import {
@ -44,9 +44,12 @@ export default function OpenStreetMap({
const [webviewContent, setWebviewContent] = useState(null);
const [markerListener, setMarkerListener] = useState(null);
if (mapRef != null) {
animateToPosition != null && goToRegion(mapRef, animateToPosition);
}
useEffect(() => {
if (mapRef != null) {
goToRegion(mapRef, animateToPosition);
}
}, [mapRef, animateToPosition]);
markersList &&
mapRef &&
notEmpy(markersList) &&
@ -76,12 +79,12 @@ export default function OpenStreetMap({
source={{ html: webviewContent }}
/>
<View>
<MapModal
markerToRender={markerListener}
setMarkerToRender={setMarkerListener}
markers={markersList}
/>
</View>
<MapModal
markerToRender={markerListener}
setMarkerToRender={setMarkerListener}
markers={markersList}
/>
</View>
<View style={styles.callback}>
<Text style={styles.txt}>{markerListener}</Text>

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";
export default function useLocation(
@ -18,7 +18,7 @@ export default function useLocation(
accuracy: Location.Accuracy.BestForNavigation,
});
setLocation({ latitude, longitude });
setLocation({ lat: latitude, long: longitude, zoom: 16.5 });
} catch (error) {
console.log(error);
}

51
src/app/screens/MapFormScreen.js

@ -1,29 +1,19 @@
import React, { useContext, useState, useEffect, memo } from "react";
import { StyleSheet, View, Text, Image } from "react-native";
import * as Location from "expo-location";
import colors from "../config/colors";
import * as Location from "expo-location";
import { EventLocationContext } from "../context/EventLocationContext";
import { TouchableOpacity } from "react-native-gesture-handler";
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)
const MapFormScreen = (props) => {
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);
console.log("=====POSIÇÃO: " + typeof location);
const getAddress = async (coordenadas) => {
Location.setGoogleApiKey("AIzaSyD_wuuokS3SVczc8qSASrsBq0E5qIpdyMc");
@ -32,9 +22,10 @@ const MapFormScreen = (props) => {
console.log(address);
console.log(coordenadas);
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);
} else {
//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
const moveLocation = (l) => {
console.log(l);
setMoveEndListener(l);
setPosition(l);
// setPosition({
// lat: l["latitude"],
// long: l["longitude"],
// zoom: 16.5,
// });
};
return (
<View style={styles.container}>
<OpenStreetMap
style={styles.mapStyle}
moveEndListener={e => moveLocation(e)}
moveEndListener={(e) => moveLocation(e)}
animateToPosition={position}
/>
<View style={styles.markerFixed}>
@ -89,15 +84,7 @@ const styles = StyleSheet.create({
backgroundColor: colors.black,
flex: 1,
justifyContent: "center",
flexDirection: "row"
},
mapStyle: {
position: "absolute",
alignSelf: "center",
top: 0,
left: 0,
right: 0,
bottom: 0,
flexDirection: "row",
},
button: {
backgroundColor: "#1976D2",
@ -128,14 +115,6 @@ const styles = StyleSheet.create({
height: "50%",
width: 40,
},
callback: {
bottom: 100,
alignSelf: "center",
alignItems: "center",
backgroundColor: "gray",
width: "80%",
padding: 10,
},
});
export default MapFormScreen;
Loading…
Cancel
Save