add: getDirections in maps

This commit is contained in:
Alexandro Uc Santos
2024-02-27 20:50:41 -06:00
parent 4301f6c7c8
commit 1ab389605d
6 changed files with 83 additions and 42 deletions

View File

@@ -24,12 +24,13 @@
const heightMap = ref(768); const heightMap = ref(768);
const originCoords = ref(null); const originCoords = ref(null);
const destinationCoords = ref(null); const destinationCoords = ref(null);
const polylines = ref([]);
const startLocation = ref(null); const startLocation = ref(null);
const endLocation = ref(null); const endLocation = ref(null);
const isLoading = ref(false); const isLoading = ref(false);
const loadingLocations = ref(false); const loadingLocations = ref(false);
const submited = ref(false); const submited = ref(false);
const { geocodeAddress } = useDirectionsRender(); const { geocodeAddress, getDirections } = useDirectionsRender();
const formRef = ref(null); const formRef = ref(null);
const filterQueryVehicles = ref([]); const filterQueryVehicles = ref([]);
const checkLocationLoad = ref(false); const checkLocationLoad = ref(false);
@@ -46,6 +47,8 @@
stateDestination: null, stateDestination: null,
}); });
const mapKey = import.meta.env.VITE_MAP_KEY;
const clearLoad = () => { const clearLoad = () => {
loadStore.currentLoad = null; loadStore.currentLoad = null;
@@ -124,6 +127,13 @@
destinationCoords.value = await geocodeAddress(endLocation.value); destinationCoords.value = await geocodeAddress(endLocation.value);
} }
}) })
watch([originCoords, destinationCoords], async() => {
if(originCoords.value && destinationCoords.value) {
console.log('Se llama api direcciones ')
polylines.value = await getDirections(originCoords.value, destinationCoords.value);
}
})
}) })
watch(locationLoadSelected, () => { watch(locationLoadSelected, () => {
@@ -510,7 +520,7 @@
v-model="locationDownloadSelected" v-model="locationDownloadSelected"
> >
<option disabled value="">-- Seleccionar locación --</option> <option disabled value="">-- Seleccionar locación --</option>
<option v-for="loc in companyStore.locations" :value="loc">{{ loc.branch_name }}</option> <option v-for="loc in companyStore.locationsLoads" :value="loc">{{ loc.branch_name }}</option>
</select> </select>
</div> </div>
<Custominput <Custominput
@@ -566,7 +576,7 @@
</div> </div>
</form> </form>
<GoogleMap <GoogleMap
api-key="AIzaSyAJtfvrAKy7vnUSv2nzk4dYQkOs3OP4MMs" :api-key="mapKey"
:center="{lat:19.432600, lng:-99.133209}" :center="{lat:19.432600, lng:-99.133209}"
:zoom="zoom" :zoom="zoom"
:min-zoom="2" :min-zoom="2"
@@ -583,13 +593,18 @@
> >
<Marker v-if="originCoords" :options="{position: originCoords, label: 'O', title: 'Destino'}" /> <Marker v-if="originCoords" :options="{position: originCoords, label: 'O', title: 'Destino'}" />
<Marker v-if="destinationCoords" :options="{position: destinationCoords, label: 'D', title: 'Origen'}" /> <Marker v-if="destinationCoords" :options="{position: destinationCoords, label: 'D', title: 'Origen'}" />
<!-- <Polyline :options="{ <Polyline
path: polyline, v-if="polylines"
:options="{
path: polylines,
// geodesic: true, // geodesic: true,
strokeColor: '#FF0000', strokeColor: '#2D90BB',
strokeOpacity: 1.0, strokeOpacity: 0.7,
strokeWeight: 2 strokeWeight: 5,
}" /> --> clickable: true,
fillColor: '#75ad3e',
}"
/>
</GoogleMap> </GoogleMap>
</div> </div>
<div class="modal-footer custom-footer"> <div class="modal-footer custom-footer">

View File

@@ -2,15 +2,17 @@
import { ref, onMounted } from 'vue'; import { ref, onMounted } from 'vue';
import CardEmpty from './CardEmpty.vue'; import CardEmpty from './CardEmpty.vue';
import Spiner from './ui/Spiner.vue'; import Spiner from './ui/Spiner.vue';
import { GoogleMap, Marker, CustomMarker } from 'vue3-google-map'; import { GoogleMap, Marker, CustomMarker, Polyline } from 'vue3-google-map';
import useDirectionsRender from '../composables/useDirectionRender'; import useDirectionsRender from '../composables/useDirectionRender';
import Cardload from './CardLoad.vue'; import Cardload from './CardLoad.vue';
import { useLoadsStore } from '../stores/loads'; import { useLoadsStore } from '../stores/loads';
const mapKey = import.meta.env.VITE_MAP_KEY;
const zoom = ref(6); const zoom = ref(6);
const heightMap = ref(768); const heightMap = ref(768);
const originCoords = ref(null); const originCoords = ref(null);
const polylines = ref([]);
const destinationCoords = ref(null); const destinationCoords = ref(null);
const isLoading = ref(false); const isLoading = ref(false);
const windowWidth = ref(window.innerWidth); const windowWidth = ref(window.innerWidth);
@@ -18,7 +20,7 @@
const vehicleLastLocation = ref(null); const vehicleLastLocation = ref(null);
const isLoadActive = ref(false); const isLoadActive = ref(false);
const { geocodeAddress } = useDirectionsRender() const { geocodeAddress, getDirections } = useDirectionsRender()
const props = defineProps({ const props = defineProps({
proposal: { proposal: {
@@ -50,6 +52,7 @@
load.value = resp.data[0]; load.value = resp.data[0];
originCoords.value = await geocodeAddress(load.value.origin_formatted_address); originCoords.value = await geocodeAddress(load.value.origin_formatted_address);
destinationCoords.value = await geocodeAddress(load.value.destination_formatted_address); destinationCoords.value = await geocodeAddress(load.value.destination_formatted_address);
polylines.value = await getDirections(originCoords.value, destinationCoords.value);
if(load.value.vehicle) { if(load.value.vehicle) {
vehicleLastLocation.value = { vehicleLastLocation.value = {
lat: parseFloat(load.value.vehicle.last_location_lat), lat: parseFloat(load.value.vehicle.last_location_lat),
@@ -113,7 +116,7 @@
<div v-if="load"> <div v-if="load">
<Cardload :load="load" :read-only="true"/> <Cardload :load="load" :read-only="true"/>
<GoogleMap <GoogleMap
api-key="AIzaSyAJtfvrAKy7vnUSv2nzk4dYQkOs3OP4MMs" :api-key="mapKey"
:center="{lat:19.432600, lng:-99.133209}" :center="{lat:19.432600, lng:-99.133209}"
:zoom="zoom" :zoom="zoom"
:min-zoom="2" :min-zoom="2"
@@ -141,13 +144,18 @@
<i class="fa-solid fa-truck" :style="{fontSize: 25 + 'px', color: 'green'}"></i> <i class="fa-solid fa-truck" :style="{fontSize: 25 + 'px', color: 'green'}"></i>
</div> </div>
</CustomMarker> </CustomMarker>
<!-- <Polyline :options="{ <Polyline
path: polyline, v-if="polylines"
:options="{
path: polylines,
// geodesic: true, // geodesic: true,
strokeColor: '#FF0000', strokeColor: '#2D90BB',
strokeOpacity: 1.0, strokeOpacity: 0.7,
strokeWeight: 2 strokeWeight: 5,
}" /> --> clickable: true,
fillColor: '#75ad3e',
}"
/>
</GoogleMap> </GoogleMap>
</div> </div>
<CardEmpty v-else text="No hay información disponible"/> <CardEmpty v-else text="No hay información disponible"/>

View File

@@ -3,7 +3,7 @@
import CardEmpty from './CardEmpty.vue'; import CardEmpty from './CardEmpty.vue';
import Spiner from './ui/Spiner.vue'; import Spiner from './ui/Spiner.vue';
import BadgeError from './ui/BadgeError.vue'; import BadgeError from './ui/BadgeError.vue';
import { GoogleMap, Marker } from 'vue3-google-map'; import { GoogleMap, Marker, Polyline } from 'vue3-google-map';
import useDirectionsRender from '../composables/useDirectionRender'; import useDirectionsRender from '../composables/useDirectionRender';
import { useAuthStore } from '../stores/auth'; import { useAuthStore } from '../stores/auth';
import { useCompanyStore } from '../stores/company'; import { useCompanyStore } from '../stores/company';
@@ -11,11 +11,13 @@
import { saveProposal } from '../services/vehicles' import { saveProposal } from '../services/vehicles'
import Swal from 'sweetalert2'; import Swal from 'sweetalert2';
const mapKey = import.meta.env.VITE_MAP_KEY;
const zoom = ref(6); const zoom = ref(6);
const heightMap = ref(768); const heightMap = ref(768);
const originCoords = ref(null); const originCoords = ref(null);
const destinationCoords = ref(null); const destinationCoords = ref(null);
const polylines = ref([]);
const isLoading = ref(false); const isLoading = ref(false);
const loadingSubmit = ref(false); const loadingSubmit = ref(false);
const windowWidth = ref(window.innerWidth); const windowWidth = ref(window.innerWidth);
@@ -28,7 +30,7 @@
comments: '', comments: '',
}); });
const { geocodeAddress } = useDirectionsRender() const { geocodeAddress, getDirections } = useDirectionsRender()
const props = defineProps({ const props = defineProps({
load: { load: {
@@ -61,6 +63,7 @@
await vehiclesStore.fetchVehicles(filterQuery); await vehiclesStore.fetchVehicles(filterQuery);
originCoords.value = await geocodeAddress(props.load.origin_formatted_address); originCoords.value = await geocodeAddress(props.load.origin_formatted_address);
destinationCoords.value = await geocodeAddress(props.load.destination_formatted_address); destinationCoords.value = await geocodeAddress(props.load.destination_formatted_address);
polylines.value = await getDirections(originCoords.value, destinationCoords.value);
isLoading.value = false; isLoading.value = false;
console.log(props.proposal); console.log(props.proposal);
if(props.proposal) { if(props.proposal) {
@@ -204,7 +207,7 @@
</form> </form>
<GoogleMap <GoogleMap
v-if="!proposal" v-if="!proposal"
api-key="AIzaSyAJtfvrAKy7vnUSv2nzk4dYQkOs3OP4MMs" :api-key="mapKey"
:center="{lat:19.432600, lng:-99.133209}" :center="{lat:19.432600, lng:-99.133209}"
:zoom="zoom" :zoom="zoom"
:min-zoom="2" :min-zoom="2"
@@ -221,13 +224,18 @@
> >
<Marker v-if="originCoords" :options="{position: originCoords, label: 'O', title: 'Destino'}" /> <Marker v-if="originCoords" :options="{position: originCoords, label: 'O', title: 'Destino'}" />
<Marker v-if="destinationCoords" :options="{position: destinationCoords, label: 'D', title: 'Origen'}" /> <Marker v-if="destinationCoords" :options="{position: destinationCoords, label: 'D', title: 'Origen'}" />
<!-- <Polyline :options="{ <Polyline
path: polyline, v-if="polylines"
:options="{
path: polylines,
// geodesic: true, // geodesic: true,
strokeColor: '#FF0000', strokeColor: '#2D90BB',
strokeOpacity: 1.0, strokeOpacity: 0.7,
strokeWeight: 2 strokeWeight: 5,
}" /> --> clickable: true,
fillColor: '#75ad3e',
}"
/>
</GoogleMap> </GoogleMap>
</div> </div>
<CardEmpty v-else text="No hay coincidencia"/> <CardEmpty v-else text="No hay coincidencia"/>

View File

@@ -10,6 +10,7 @@
const polyline = ref([]); const polyline = ref([]);
// const startLocation = ref({ lat: 37.7749, lng: -122.4194 }); // San Francisco // const startLocation = ref({ lat: 37.7749, lng: -122.4194 }); // San Francisco
// const endLocation = ref({ lat: 34.0522, lng: -118.2437 }); // Los Angeles // const endLocation = ref({ lat: 34.0522, lng: -118.2437 }); // Los Angeles
const mapKey = import.meta.env.VITE_MAP_KEY;
onMounted(async() => { onMounted(async() => {
window.addEventListener('resize', handleResize); window.addEventListener('resize', handleResize);
@@ -80,7 +81,7 @@
<template> <template>
<GoogleMap <GoogleMap
api-key="AIzaSyAJtfvrAKy7vnUSv2nzk4dYQkOs3OP4MMs" :api-key="mapKey"
:center="{lat:19.432600, lng:-99.133209}" :center="{lat:19.432600, lng:-99.133209}"
:zoom="zoom" :zoom="zoom"
:min-zoom="2" :min-zoom="2"

View File

@@ -3,18 +3,19 @@ import { decode } from 'polyline';
export default function useDirectionsRender() { export default function useDirectionsRender() {
const mapKey = import.meta.env.VITE_MAP_KEY;
const originCoords = ref(null); const originCoords = ref(null);
const destinationCoords = ref(null); const destinationCoords = ref(null);
const polylines = ref([]); // const polylines = ref([]);
const geocodeAddress = async (address) => { const geocodeAddress = async (address) => {
// Utiliza la API de geocodificación de Google Maps para obtener las coordenadas // Utiliza la API de geocodificación de Google Maps para obtener las coordenadas
const apiKey = 'AIzaSyBm3n6I_uMzKkMS0eVXnLdoa1S_hPcsx0A'; // Reemplaza con tu clave de API
// const apiKey = 'AIzaSyAJtfvrAKy7vnUSv2nzk4dYQkOs3OP4MMs'; // Reemplaza con tu clave de API // const apiKey = 'AIzaSyAJtfvrAKy7vnUSv2nzk4dYQkOs3OP4MMs'; // Reemplaza con tu clave de API
try { try {
const response = await fetch( const response = await fetch(
`https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent( `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(
address address
)}&key=${apiKey}` )}&key=${mapKey}`
); );
const data = await response.json(); const data = await response.json();
const location = data.results[0].geometry.location; const location = data.results[0].geometry.location;
@@ -25,28 +26,32 @@ export default function useDirectionsRender() {
}; };
const getDirections = async (originCoords, destinationCoords) => { const getDirections = async (originCoords, destinationCoords) => {
console.log('GET directions,', originCoords)
const apiKey = 'AIzaSyBm3n6I_uMzKkMS0eVXnLdoa1S_hPcsx0A';
const originLatLng = `${originCoords.lat},${originCoords.lng}`; const originLatLng = `${originCoords.lat},${originCoords.lng}`;
const destinationLatLng = `${destinationCoords.lat},${destinationCoords.lng}`; const destinationLatLng = `${destinationCoords.lat},${destinationCoords.lng}`;
try { try {
let url = `https://maps.googleapis.com/maps/api/directions/json?origin=${originLatLng}&destination=${destinationLatLng}&mode=driving&key=${apiKey}`; let url = `https://maps.googleapis.com/maps/api/directions/json?origin=${originLatLng}&destination=${destinationLatLng}&mode=driving&key=${mapKey}`;
const response = await fetch(url); const response = await fetch(url);
const data = await response.json(); const data = await response.json();
let polylines = [];
if (data.routes && data.routes.length > 0) { if (data.routes && data.routes.length > 0) {
const steps = data.routes[0].legs[0].steps; const steps = data.routes[0].legs[0].steps;
steps.forEach(item => { steps.forEach(item => {
const points = decode(item.polyline.points); const points = decode(item.polyline.points);
points.forEach(poly => { points.forEach(poly => {
polylines.value.push({ polylines.push({
lat: poly[0], lat: poly[0],
lng: poly[1] lng: poly[1]
}) })
}) })
}); });
console.log(polylines)
return polylines;
} else {
return [];
} }
} catch (error) { } catch (error) {
console.log(error); console.log(error);
return [];
} }
}; };
@@ -54,6 +59,6 @@ export default function useDirectionsRender() {
originCoords, originCoords,
geocodeAddress, geocodeAddress,
getDirections, getDirections,
polylines // polylines
} }
} }

View File

@@ -8,9 +8,11 @@
import { GoogleMap, Marker, CustomMarker, Polyline } from 'vue3-google-map'; import { GoogleMap, Marker, CustomMarker, Polyline } from 'vue3-google-map';
import CardEmpty from '../components/CardEmpty.vue'; import CardEmpty from '../components/CardEmpty.vue';
const mapKey = import.meta.env.VITE_MAP_KEY;
const isLoading = ref(true); const isLoading = ref(true);
const loadStore = useLoadsStore(); const loadStore = useLoadsStore();
const { geocodeAddress, getDirections, polylines } = useDirectionsRender() const { geocodeAddress, getDirections } = useDirectionsRender()
const route = useRoute(); const route = useRoute();
const load = ref(null); const load = ref(null);
const zoom = ref(6); const zoom = ref(6);
@@ -18,6 +20,7 @@
const vehicleLastLocation = ref(null); const vehicleLastLocation = ref(null);
const originCoords = ref(null); const originCoords = ref(null);
const destinationCoords = ref(null); const destinationCoords = ref(null);
const polylines = ref([]);
const isLoadActive = ref(false); const isLoadActive = ref(false);
const windowWidth = ref(window.innerWidth); const windowWidth = ref(window.innerWidth);
@@ -47,7 +50,7 @@
console.log(vehicleLastLocation); console.log(vehicleLastLocation);
} }
await getDirections(originCoords.value, destinationCoords.value); polylines.value = await getDirections(originCoords.value, destinationCoords.value);
console.log(load.value.load_status); console.log(load.value.load_status);
switch (load.value.load_status) { switch (load.value.load_status) {
@@ -89,7 +92,7 @@
<div v-if="load"> <div v-if="load">
<CardLoad :load="load" :read-only="true"/> <CardLoad :load="load" :read-only="true"/>
<GoogleMap <GoogleMap
api-key="AIzaSyBm3n6I_uMzKkMS0eVXnLdoa1S_hPcsx0A" :api-key="mapKey"
:center="{lat:19.432600, lng:-99.133209}" :center="{lat:19.432600, lng:-99.133209}"
:zoom="zoom" :zoom="zoom"
:min-zoom="2" :min-zoom="2"
@@ -118,6 +121,7 @@
</div> </div>
</CustomMarker> </CustomMarker>
<Polyline <Polyline
v-if="polylines"
:options="{ :options="{
path: polylines, path: polylines,
// geodesic: true, // geodesic: true,