add: map directions & set data load in form edit

This commit is contained in:
Alexandro Uc Santos
2023-12-09 19:58:37 -06:00
parent cea26e1f6e
commit bb6cd37532
10 changed files with 393 additions and 161 deletions

View File

@@ -17,6 +17,11 @@
loadsStore.currentLoad = props.load;
}
const openEditModal = () => {
loadsStore.openModalEdit = true;
loadsStore.currentLoad = props.load
}
</script>
<template>
@@ -76,7 +81,8 @@
</button>
<button
class="btn-primary-sm"
data-toggle="modal" data-target="#editcompanymodal"
data-toggle="modal" data-target="#formLoadModal"
@click="openEditModal"
><i class="fa-solid fa-pen-to-square clear-sm"></i> Editar carga</button>
<button
class="btn-primary-sm"

View File

@@ -1,69 +1,31 @@
<script setup>
import { onMounted, reactive, ref } from 'vue';
import { GoogleMap, Marker } from "vue3-google-map";
import { reactive, ref, onMounted, watch } from 'vue';
import { useLoadsStore } from '../stores/loads';
import Custominput from './ui/custominput.vue';
import Segments from './ui/Segments.vue';
import TruckTypes from './ui/TruckTypes.vue';
import Cities from './ui/Cities.vue';
import States from './ui/States.vue';
import Products from './ui/Products.vue';
import { GoogleMap, Marker, Polyline } from "vue3-google-map";
import useDirectionsRender from '../composables/useDirectionRender';
const props = defineProps({
load: {
type: Object,
required: false
}
})
// const startLocation = ref({query: 'C. 40 370, San Román, 97540 Izamal, Yuc.'});
// const endLocation = ref({query: 'Izamal-Valladolid, 97557 Sudzal, Yuc.'})
const startLocation = ref({ lat: 37.7749, lng: -122.4194 }); // San Francisco
const endLocation = ref({ lat: 34.0522, lng: -118.2437 }); // Los Angeles
const loadStore = useLoadsStore();
const windowWidth = ref(window.innerWidth);
const zoom = ref(6);
const heightMap = ref(768);
const originCoords = ref(null);
const destinationCoords = ref(null);
const startLocation = ref(null);
const endLocation = ref(null);
const { geocodeAddress } = useDirectionsRender();
const clearLoad = () => {
loadStore.currentLoad = null;
loadStore.openModalEdit = false;
}
const formLoad = reactive({
dateLoad: '',
dateDownload: '',
segment: [],
truckType: [],
terms: [],
price: 0,
weigth: 0,
notes: '',
owner: '',
locationNameOrigin: '',
addressOrigin: '',
stateOrigin: '',
cityOrigin: '',
countryOrigin: '',
postalCodeOrigin: '',
refOrigin: '',
locationNameDestination: '',
addressDestination: '',
stateDestination: '',
cityDestination: '',
countryDestination: '',
postalCodeDestination: '',
refDestination: '',
});
onMounted(() => {
window.addEventListener('resize', handleResize);
if(window.innerWidth <= 1024) {
zoom.value = 4;
heightMap.value = 420;
}
});
const handleResize = () => {
windowWidth.value = window.innerWidth
if(windowWidth.value <= 1024){
@@ -75,26 +37,107 @@
}
}
const onApiLoaded = () => {
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(mapRef.value.$map);
// Configurar solicitud de dirección
const request = {
origin: startLocation.value,
destination: endLocation.value,
travelMode: google.maps.TravelMode.DRIVING,
};
// Obtener ruta
directionsService.route(request, (response, status) => {
if (status === 'OK') {
directionsRenderer.setDirections(response);
} else {
console.error('Error al trazar la ruta:', status);
onMounted(() => {
window.addEventListener('resize', handleResize);
// mapRef.value = this.$refs.myMap;
if(window.innerWidth <= 1024) {
zoom.value = 4;
heightMap.value = 420;
}
//origin_formatted_address
if(loadStore.currentLoad){
formLoad.price = loadStore.currentLoad.actual_cost;
formLoad.segment = loadStore.currentLoad.categories.map(m =>{
return { name: m.name };
});
};
startLocation.value = loadStore.currentLoad.origin_formatted_address;
endLocation.value = loadStore.currentLoad.destination_formatted_address;
formLoad.terms = {name: loadStore.currentLoad.product.name};
formLoad.owner = loadStore.currentLoad.posted_by_name;
formLoad.notes = loadStore.currentLoad.notes;
formLoad.weight = loadStore.currentLoad.weight;
formLoad.dateLoad = loadStore.currentLoad.est_loading_date.substring(0, 10);
formLoad.dateDownload = loadStore.currentLoad.est_unloading_date.substring(0, 10);
formLoad.truckType = {meta_value: loadStore.currentLoad.truck_type};
origin.locationNameOrigin = loadStore.currentLoad.origin.company_name;
origin.addressOrigin = loadStore.currentLoad.origin.street_address1;
origin.stateOrigin = { state_name: loadStore.currentLoad.origin.state };
origin.cityOrigin = { city_name: loadStore.currentLoad.origin.city };
origin.countryOrigin = loadStore.currentLoad.origin.country;
origin.postalCodeOrigin = loadStore.currentLoad.origin.zipcode;
origin.refOrigin = loadStore.currentLoad.origin.landmark;
destination.locationNameDestination = loadStore.currentLoad.destination.company_name;
destination.addressDestination = loadStore.currentLoad.destination.street_address1;
destination.stateDestination = { state_name: loadStore.currentLoad.destination.state };
destination.cityDestination = { city_name: loadStore.currentLoad.destination.city };
destination.countryDestination = loadStore.currentLoad.destination.country;
destination.postalCodeDestination = loadStore.currentLoad.destination.zipcode;
destination.refDestination = loadStore.currentLoad.destination.landmark;
getCoordsMap();
watch(origin, async() => {
startLocation.value = origin.addressOrigin + ', ' + origin.cityOrigin.city_name + ', ' + origin.stateOrigin.state_name + ', ' + origin.countryOrigin + ', ' +origin.postalCodeOrigin;
originCoords.value = await geocodeAddress(startLocation.value);
console.log('Origin:')
console.log(originCoords.value)
})
watch(destination, async() => {
endLocation.value = destination.addressDestination + ', ' + destination.cityDestination.city_name + ', ' + destination.stateDestination.state_name + ', ' + destination.countryDestination + ', ' +destination.postalCodeDestination;
destinationCoords.value = await geocodeAddress(endLocation.value);
console.log('Destination:')
console.log(destinationCoords.value);
})
}
})
const getCoordsMap = async() => {
originCoords.value = await geocodeAddress(loadStore.currentLoad.origin_formatted_address);
destinationCoords.value = await geocodeAddress(loadStore.currentLoad.destination_formatted_address);
}
const formLoad = reactive({
dateLoad: '',
dateDownload: '',
segment: [],
truckType: [],
terms: [],
price: 0,
weight: 0,
notes: '',
owner: '',
});
const origin = reactive({
locationNameOrigin: '',
addressOrigin: '',
stateOrigin: '',
cityOrigin: '',
countryOrigin: '',
postalCodeOrigin: '',
refOrigin: '',
});
const destination = reactive({
locationNameDestination: '',
addressDestination: '',
stateDestination: '',
cityDestination: '',
countryDestination: '',
postalCodeDestination: '',
refDestination: '',
});
const handleSave = () => {
console.log(formLoad);
console.log(origin)
console.log(destination)
}
</script>
<template>
@@ -119,14 +162,14 @@
<div class="form-section">
<div class="mb-4 mt-3">
<label class="custom-label">Segmento*</label>
<TruckTypes
v-model="formLoad.truckType"
<Segments
v-model="formLoad.segment"
/>
</div>
<div class="mb-4 mt-3">
<label class="custom-label">Tipo de transporte*</label>
<Segments
v-model="formLoad.segment"
<TruckTypes
v-model="formLoad.truckType"
/>
</div>
<Custominput
@@ -148,7 +191,7 @@
type="number"
:filled="false"
name="weight"
v-model:field="formLoad.weigth"
v-model:field="formLoad.weight"
/>
</div>
<div class="form-section">
@@ -189,25 +232,25 @@
type="text"
:filled="false"
name="name-location-origin"
v-model:field="formLoad.locationNameOrigin"
v-model:field="origin.locationNameOrigin"
/>
<Custominput
label="Dirección*"
type="text"
:filled="false"
name="address-origin"
v-model:field="formLoad.addressOrigin"
v-model:field="origin.addressOrigin"
/>
<div class="mb-4 mt-3">
<label class="custom-label">Ciudad*</label>
<Cities
v-model="formLoad.cityOrigin"
v-model="origin.cityOrigin"
/>
</div>
<div class="mb-4 mt-3">
<label class="custom-label">Estado*</label>
<Cities
v-model="formLoad.stateOrigin"
<States
v-model="origin.stateOrigin"
/>
</div>
<Custominput
@@ -215,21 +258,21 @@
type="text"
:filled="false"
name="country-origin"
v-model:field="formLoad.countryOrigin"
v-model:field="origin.countryOrigin"
/>
<Custominput
label="Código Postal*"
type="text"
:filled="false"
name="postalCode-origin"
v-model:field="formLoad.postalCodeOrigin"
v-model:field="origin.postalCodeOrigin"
/>
<Custominput
label="Punto de referencia"
type="text"
:filled="false"
name="ref-origin"
v-model:field="formLoad.refOrigin"
v-model:field="origin.refOrigin"
/>
</div>
<div class="form-section">
@@ -239,25 +282,25 @@
type="text"
:filled="false"
name="name-location-destination"
v-model:field="formLoad.locationNameDestination"
v-model:field="destination.locationNameDestination"
/>
<Custominput
label="Dirección"
type="text"
:filled="false"
name="address-destination"
v-model:field="formLoad.addressDestination"
v-model:field="destination.addressDestination"
/>
<div class="mb-4 mt-3">
<label class="custom-label">Ciudad*</label>
<Cities
v-model="formLoad.cityDestination"
v-model="destination.cityDestination"
/>
</div>
<div class="mb-4 mt-3">
<label class="custom-label">Estado*</label>
<Cities
v-model="formLoad.stateDestination"
<States
v-model="destination.stateDestination"
/>
</div>
<Custominput
@@ -265,24 +308,25 @@
type="text"
:filled="false"
name="country-destination"
v-model:field="formLoad.countryDestination"
v-model:field="destination.countryDestination"
/>
<Custominput
label="Código Postal*"
type="text"
:filled="false"
name="postalCode-destination"
v-model:field="formLoad.postalCodeDestination"
v-model:field="destination.postalCodeDestination"
/>
<Custominput
label="Punto de referencia"
type="text"
:filled="false"
name="ref-destination"
v-model:field="formLoad.refDestination"
v-model:field="destination.refDestination"
/>
</div>
</div>
</form>
<GoogleMap
api-key="AIzaSyAJtfvrAKy7vnUSv2nzk4dYQkOs3OP4MMs"
:center="{lat:19.432600, lng:-99.133209}"
@@ -298,12 +342,17 @@
rotateControl: true,
fullscreenControl: true
}"
@api-loaded="onApiLoaded"
>
<Marker :options="{position: startLocation}" />
<Marker :options="{position: endLocation}" />
<Marker v-if="originCoords" :options="{position: originCoords, label: 'O', title: 'Destino'}" />
<Marker v-if="destinationCoords" :options="{position: destinationCoords, label: 'D', title: 'Origen'}" />
<!-- <Polyline :options="{
path: polyline,
// geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
}" /> -->
</GoogleMap>
</form>
</div>
<div class="modal-footer custom-footer">
<button
@@ -314,7 +363,7 @@
<button
type="button"
class="btn btn-dark"
@click=""
@click="handleSave"
>Guardar</button>
<button
type="button"

View File

@@ -0,0 +1,112 @@
<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 startLocation = ref({ lat: 37.7749, lng: -122.4194 }); // San Francisco
// const endLocation = ref({ lat: 34.0522, lng: -118.2437 }); // Los Angeles
onMounted(async() => {
window.addEventListener('resize', handleResize);
// mapRef.value = this.$refs.myMap;
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.');
// Trazar la ruta entre el origen y el destino
// await getDirections();
});
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=${apiKey}`
);
const data = await response.json();
const location = data.results[0].geometry.location;
console.log('location: ', location);
return location;
};
const getDirections = async () => {
const apiKey = 'AIzaSyAJtfvrAKy7vnUSv2nzk4dYQkOs3OP4MMs';
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=${apiKey}`
);
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="AIzaSyAJtfvrAKy7vnUSv2nzk4dYQkOs3OP4MMs"
: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>

View File

@@ -1,38 +1,43 @@
export default function useDirectionRender() {
// import { MapElementFactory } from "vue2-google-map";
defineProps({
origin: { type: Object },
destination: { type: Object },
travelMode: { type: String },
})
// export default MapElementFactory({
// name: "directionsRenderer",
const directionsRenderer = ref(null);
const directionsService = new window.google.maps.DirectionsService();
// ctr() {
// return google.maps.DirectionsRenderer;
// },
onMounted(() => {
directionsRenderer.value = new window.google.maps.DirectionsRenderer();
// events: [],
watch(
() => [props.origin, props.destination, props.travelMode],
() => {
const { origin, destination, travelMode } = props;
if (!origin || !destination || !travelMode) return;
// mappedProps: {},
directionsService.route(
{
origin,
destination,
travelMode,
},
(response, status) => {
if (status !== 'OK') return;
directionsRenderer.value.setDirections(response);
}
);
},
{ immediate: true }
);
});
// props: {
// origin: { type: Object },
// destination: { type: Object },
// travelMode: { type: String }
// },
return { directionsRenderer };
}
// afterCreate(directionsRenderer) {
// let directionsService = new google.maps.DirectionsService();
// this.$watch(
// () => [this.origin, this.destination, this.travelMode],
// () => {
// let { origin, destination, travelMode } = this;
// if (!origin || !destination || !travelMode) return;
// directionsService.route(
// {
// origin,
// destination,
// travelMode
// },
// (response, status) => {
// if (status !== "OK") return;
// directionsRenderer.setDirections(response);
// }
// );
// }
// );
// }
// });

View File

@@ -1,7 +1,7 @@
<script setup>
defineProps({
const props = defineProps({
field: {
type: [String, Number]
type: [String, Number, Date]
},
label: {
type: String,
@@ -27,6 +27,7 @@
})
defineEmits(['update:field'])
</script>
<template>

View File

@@ -0,0 +1,54 @@
import { ref } from "vue";
export default function useDirectionsRender() {
const originCoords = ref(null);
const destinationCoords = ref(null);
const polylines = ref([]);
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
try {
const response = await fetch(
`https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(
address
)}&key=${apiKey}`
);
const data = await response.json();
const location = data.results[0].geometry.location;
return location;
} catch (error) {
return null;
}
};
const getDirections = async () => {
const apiKey = 'AIzaSyAJtfvrAKy7vnUSv2nzk4dYQkOs3OP4MMs';
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=${apiKey}`
);
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,
}));
polylines.value = routePolyline;
}
} catch (error) {
console.log(error);
}
};
return {
originCoords,
geocodeAddress,
getDirections,
polylines
}
}

View File

@@ -1,5 +1,4 @@
import './assets/main.css'
import { createApp } from 'vue'
import { createPinia } from 'pinia'

View File

@@ -1,6 +1,5 @@
import { defineStore } from "pinia";
import { ref } from "vue";
import { useAuthStore } from "./auth";
import { getCompany } from "../services/company";
import api from "../lib/axios";
@@ -8,7 +7,6 @@ export const useCompanyStore = defineStore('company', () => {
const companyid = localStorage.getItem('id');
const company = ref(null)
const loads = ref([])
const proposals = ref([])
const loading = ref(false);
@@ -28,24 +26,6 @@ export const useCompanyStore = defineStore('company', () => {
loading.value = false;
}
const getCompanyLoads = async(filterQuery) => {
let filterArr = Object.values(filterQuery);
let cleanfilterArr = filterArr.filter(n=>n);
var filterStr = "";
if(cleanfilterArr.length >0){
filterStr = cleanfilterArr.join("&");
}
console.log(filterStr);
try {
const endpoint = `/loads?company=${companyid}&${filterStr}`;
console.log(endpoint);
const {data} = await api.get(endpoint);
loads.value = data.data;
} catch (error) {
loads.value = [];
console.log(error);
}
}
///loads?company=64fa70c130d2650011ac4f3a&status[$ne]=Closed,posted_by_name[$regex]=ju&posted_by_name[$options]=i
@@ -65,11 +45,9 @@ export const useCompanyStore = defineStore('company', () => {
return {
getCompanyData,
getCompanyLoads,
getProposalsCompany,
clear,
loading,
loads,
proposals,
company,
}

View File

@@ -1,11 +1,38 @@
import { defineStore } from "pinia";
import { ref } from "vue";
import api from "../lib/axios";
export const useLoadsStore = defineStore('load', () => {
const companyid = localStorage.getItem('id');
const currentLoad = ref(null);
const loads = ref([])
const openModalEdit = ref(false);
const getCompanyLoads = async(filterQuery) => {
let filterArr = Object.values(filterQuery);
let cleanfilterArr = filterArr.filter(n=>n);
var filterStr = "";
if(cleanfilterArr.length >0){
filterStr = cleanfilterArr.join("&");
}
console.log(filterStr);
try {
const endpoint = `/loads?company=${companyid}&${filterStr}`;
console.log(endpoint);
const {data} = await api.get(endpoint);
loads.value = data.data;
} catch (error) {
loads.value = [];
console.log(error);
}
}
return {
currentLoad
currentLoad,
openModalEdit,
getCompanyLoads,
loads,
}
});

View File

@@ -27,13 +27,13 @@
const getDataLoadsInit = async() => {
filterQuery.value.status = "status[$ne]="+"Closed";
loading.value = true;
await companyStore.getCompanyLoads(filterQuery.value);
await loadStore.getCompanyLoads(filterQuery.value);
loading.value = false;
}
const getLoadWithFilters = async(filter) => {
loading.value = true;
await companyStore.getCompanyLoads(filter);
await loadStore.getCompanyLoads(filter);
loading.value = false;
}
@@ -66,7 +66,7 @@
<template>
<AttachmentsModal v-if="loadStore.currentLoad"/>
<FormLoadModal/>
<FormLoadModal v-if="loadStore.openModalEdit"/>
<div>
<h2 class="title mb-5">Mis cargas publicadas</h2>
<div>
@@ -86,12 +86,13 @@
<button
class="btn-primary-sm radius-sm"
data-toggle="modal" data-target="#formLoadModal"
@click="loadStore.openModalEdit = true"
><i class="fa-solid fa-plus"></i> <span class="clear-sm"> Crear</span><span class="clear-md"> carga</span></button>
</div>
<Spiner v-if="loading"/>
<CardLoad
v-else
v-for="load in companyStore.loads"
v-for="load in loadStore.loads"
:key="load._id"
:load="load"
/>