Skip to content

Commit

Permalink
Maps working with leaflet and fix resposive problems
Browse files Browse the repository at this point in the history
  • Loading branch information
antongomez committed Mar 5, 2023
1 parent 2bfe2d5 commit a06d886
Show file tree
Hide file tree
Showing 4 changed files with 163 additions and 37 deletions.
57 changes: 57 additions & 0 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"bootstrap": "^5.2.3",
"bootstrap-switch-button-react": "^1.2.0",
"leaflet": "^1.9.3",
"leaflet-routing-machine": "^3.2.12",
"react": "^18.2.0",
"react-bootstrap": "^2.7.2",
"react-dom": "^18.2.0",
Expand Down
80 changes: 59 additions & 21 deletions frontend/src/Inicio.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { useNavigate } from 'react-router';
import ButtonGroup from 'react-bootstrap/ButtonGroup';
import ToggleButton from 'react-bootstrap/ToggleButton';
import BootstrapSwitchButton from 'bootstrap-switch-button-react';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import { MapContainer, TileLayer, Marker, Popup, useMapEvents } from 'react-leaflet';
import { useMapEvent } from 'react-leaflet/hooks';
import 'leaflet/dist/leaflet.css';

Expand Down Expand Up @@ -38,6 +38,11 @@ export const Inicio = () => {
const [indiceActividad, setIndiceActividad] = useState(0);
const [usarGPS, setUsarGPS] = useState(false);
const [localizacionError, setLocalizacionError] = useState(false);
const [localizationErrorCode, setLocalizationErrorCode] = useState(undefined);
const [buscandoLoc, setBuscandoLoc] = useState(false);

/* Almacena o mapa de openmaps para depois poder usar un evento dende o swich button */
let mapa = null;

const posiblesDias = {
'Hoxe': 0,
Expand All @@ -55,6 +60,7 @@ export const Inicio = () => {
}

function LocationMarker() {
/* Hook providing the Leaflet Map instance in any descendant of a MapContainer */
const map = useMapEvent('click', (e) => {
setLatitud(e.latlng.lat);
setLongitud(e.latlng.lng);
Expand All @@ -69,13 +75,36 @@ export const Inicio = () => {
)
}

function LocationFound() {
const map = useMapEvents({
locationfound(location) {
setBuscandoLoc(false);
setLatitud(location.latlng.lat);
setLongitud(location.latlng.lng);
setLocalizacionError(false);
map.flyTo(location.latlng, map.getZoom())
},

locationerror(error) {
setBuscandoLoc(false);
setLocalizationErrorCode(error.code);
console.log("Codigo de erro " + error.code + ": " + error.message);
}
})

/* Deste xeito podemos acceder aos metodos de map dende un componhente de fora de MapContainer */
mapa = map;

return null
}

return (
<div>
<div className="py-4 px-5 justify-content-center align-items-center">
<h1 className="text-center pb-3">Imos á praia?</h1>
<Form>
<Row className="align-items-center justify-content-center pb-4">
<Col sm={3}>
<Col lg={3} className="mb-4">
<Form.Label>Que día queres ir?</Form.Label>
<div>
<ButtonGroup>
Expand Down Expand Up @@ -117,24 +146,32 @@ export const Inicio = () => {

<Form.Group>
<Form.Label >Usar a túa ubicación actual</Form.Label>
<div>
<BootstrapSwitchButton
checked={usarGPS}
onChange={(checked) => {
if (checked) {
navigator.geolocation.getCurrentPosition((location) => {
setLatitud(location.coords.latitude);
setLongitud(location.coords.longitude);
setLocalizacionError(false);
});
setUsarGPS(true);
} else {
setLatitud(undefined);
setLongitud(undefined);
setUsarGPS(false);
}
}}
/>
<div className="container px-0 mx-0">
<Row className="d-flex">
<Col className="flex-grow-0">
<BootstrapSwitchButton
checked={usarGPS}
onChange={(checked) => {
if (checked) {
/* Se en 10 segundos non se obten a localizacion salta un erro */
mapa.locate({timeout:10000});
setUsarGPS(true);
setBuscandoLoc(true);
} else {
setLatitud(undefined);
setLongitud(undefined);
setUsarGPS(false);
}
}}
/>
</Col>
<Col className="d-flex align-items-center flex-grow-1 ps-1">
{buscandoLoc ? (<p className="text-secondary my-0">Buscando...</p>) : null}
</Col>
</Row>
<Row className="justify-content-start align-items-center pt-2">
{localizationErrorCode !== 3 ? null : (<p className="text-danger">Non se puido ober a túa localizacion</p>)}
</Row>
</div>
<Form.Label className="mb-1 mt-4">Alternativamente, podes seleccionar un punto de partida</Form.Label>
<div class="bg-primary">
Expand All @@ -151,14 +188,15 @@ export const Inicio = () => {
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<LocationFound />
<LocationMarker />
</MapContainer>
</div>
</Form.Group>

</Col>

<Col sm={7}>
<Col lg={7}>
<Row className="mb-5 justify-content-center align-items-top">
<img style={{ cursor: "pointer" }} className="col-1" src="assets/leftArrow.svg" onClick={() => {
setIndiceActividad(indiceActividad === 0 ? actividades.length - 1 : indiceActividad - 1);
Expand Down
62 changes: 46 additions & 16 deletions frontend/src/Resultados.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,14 @@ import { useEffect, useState } from 'react';
import { URL_BACKEND } from "../package.json";
import ClipLoader from 'react-spinners/ClipLoader';

import L from "leaflet";
import { createControlComponent } from "@react-leaflet/core";
import { MapContainer, TileLayer } from 'react-leaflet';

import 'leaflet-routing-machine';

import 'leaflet/dist/leaflet.css';
import 'leaflet-routing-machine/dist/leaflet-routing-machine.css'

export const Resultados = () => {
const location = useLocation();
Expand Down Expand Up @@ -38,7 +44,7 @@ export const Resultados = () => {
return (
<div class="my-4">
<Row className="px-5 justify-content-center">
<Col sm={4}>
<Col lg={4}>
<h3 class="text-center">Sentímolo moito, tivo lugar un erro cargando a páxina. </h3>
</Col>
</Row>
Expand Down Expand Up @@ -69,26 +75,47 @@ export const Resultados = () => {
const containerStyle = {
width: '100 %',
height: '350px'
};

const createRouting = (props) => {
const instance = L.Routing.control({
waypoints: [
L.latLng(props.ori.lat, props.ori.lng),
L.latLng(props.dest.lat, props.dest.lng)
],

show: false, /* Para que non se mostren as indicacions nada mais cargar o mapa*/
addWaypoints: false,
draggableWaypoints: false,
fitSelectedRoutes: false,
showAlternatives: false
});

/* Cando se atope a ruta actualizamos a distancia e o tempo*/
instance.on('routesfound', function(routeResult) {
setDistancia(Math.round(routeResult.routes[0].summary.totalDistance/1000));
setTiempo(Math.round(routeResult.routes[0].summary.totalTime/60));
})

return instance;
};
const defaultCenter = {
lat: 43.3322352,
lng: -8.4106015,
}

const Routing = createControlComponent(createRouting);

return (
<div class="d-flex flex-column">
<Row className="mx-4 mt-4 mb-2">
<Col sm={1}>
<Col lg={1}>
<Button variant="outline-secondary" href="/" >Volver</Button>{' '}
</Col>
</Row>
<Row className="mb-4">
<Col sm={12}>
<Col lg={12}>
<h2 class="text-center">Aquí tes as mellores praias para <strong>{actividad}</strong></h2>
</Col>
</Row>
<Row className="px-5 justify-content-center pt-4">
<Col sm={3} className="me-5">
<Row className="px-5 justify-content-center pt-4 gy-5 gx-5">
<Col lg={3}>
<h4 class="text-center">Ranking de praias</h4>
<ListGroup as="ol" numbered>
{rankingPlayas.slice(0, 5).map((playa, index) => {
Expand All @@ -105,28 +132,31 @@ export const Resultados = () => {
</ListGroup>
</Col>

<Col sm={6} className="ms-5">
<Col lg={6}>
< Row className="p-2 border border-secondary shadow border-2 rounded">
<Col sm={5}>
<Col md={5}>
<h4 className="text-center"><u>{rankingPlayas[playaActiva].nombre}</u></h4>
<p>{"Vento: " + playas[rankingPlayas[playaActiva].nombre].viento + " Km/h"}</p>
<p>{"Temperatura: " + playas[rankingPlayas[playaActiva].nombre].temperatura + " ºC"}</p>
<p>{"Cobertura de nubes: " + playas[rankingPlayas[playaActiva].nombre].coberturaNubes + " %"}</p>
<p>{"Distancia en coche: " + distancia}</p>
<p>{"Tempo estimado de traxecto: " + tiempo}</p>
<p>{"Distancia en coche: " + distancia + " km"}</p>
<p>{"Tempo estimado de traxecto: " + tiempo + " min"}</p>
</Col>
<Col>
<Col md={7}>
<div className="px-0 py-1 w-100 h-100">
<MapContainer
center={destino}
zoom={10}
/* Punto medio da ruta */
center={{lat: (orixe.lat + destino.lat)/2, lng: (orixe.lng + destino.lng)/2}}
zoom={9}
scrollWheelZoom={false}
style={containerStyle}
>

<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Routing ori={orixe} dest={destino} />
</MapContainer>

</div>
Expand Down

0 comments on commit a06d886

Please sign in to comment.