Files
WebETA/src/components/MapDirections.vue
2024-09-25 20:27:00 -06:00

106 lines
3.4 KiB
Vue

<script setup>
import { onMounted, ref } from "vue";
import { GoogleMap, Marker, Polyline } from "vue3-google-map";
const windowWidth = ref(window.innerWidth);
const zoom = ref(6);
const heightMap = ref(768);
const originCoords = ref(null);
const destinationCoords = ref(null);
const polyline = ref([]);
const mapKey = import.meta.env.VITE_MAP_KEY;
onMounted(async() => {
window.addEventListener('resize', handleResize);
if(window.innerWidth <= 1024) {
zoom.value = 4;
heightMap.value = 420;
}
originCoords.value = await geocodeAddress('C. 40 370, San Román, 97540 Izamal, Yuc.');
destinationCoords.value = await geocodeAddress('Izamal-Valladolid, 97557 Sudzal, Yuc.');
});
const handleResize = () => {
windowWidth.value = window.innerWidth
if(windowWidth.value <= 1024){
zoom.value = 4
heightMap.value = 420;
} else {
zoom.value = 6;
heightMap.value = 768;
}
}
const geocodeAddress = async (address) => {
// Utiliza la API de geocodificación de Google Maps para obtener las coordenadas
// const apiKey = 'AIzaSyAJtfvrAKy7vnUSv2nzk4dYQkOs3OP4MMs'; // Reemplaza con tu clave de API
const response = await fetch(
`https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(
address
)}&key=${mapKey}`
);
const data = await response.json();
const location = data.results[0].geometry.location;
console.log('location: ', location);
return location;
};
const getDirections = async () => {
const originLatLng = `${originCoords.value.lat},${originCoords.value.lng}`;
const destinationLatLng = `${destinationCoords.value.lat},${destinationCoords.value.lng}`;
try {
const response = await fetch(
`https://maps.googleapis.com/maps/api/directions/json?origin=${originLatLng}&destination=${destinationLatLng}&key=${mapKey}`
);
const data = await response.json();
if (data.routes && data.routes.length > 0) {
const steps = data.routes[0].legs[0].steps;
const routePolyline = steps.map((step) => ({
lat: step.end_location.lat,
lng: step.end_location.lng,
}));
polyline.value = routePolyline;
}
} catch (error) {
console.log(error);
}
};
</script>
<template>
<GoogleMap
:api-key="mapKey"
:center="{lat:19.432600, lng:-99.133209}"
:zoom="zoom"
:min-zoom="2"
:max-zoom="12"
:style="{width: 100 + '%', height: heightMap + 'px'}"
:options="{
zoomControl: true,
mapTypeControl: true,
scaleControl: true,
streetViewControl: true,
rotateControl: true,
fullscreenControl: true
}"
>
<Marker :options="{position: originCoords, label: 'O', title: 'Destino'}" />
<Marker :options="{position: destinationCoords, label: 'D', title: 'Origen'}" />
<Polyline :options="{
path: polyline,
// geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
}" />
</GoogleMap>
</template>
<style scoped>
</style>