/* map_autocomplete.js */ var autocomplete = null; const validateMapPlaceResult = { Ok: 0, Empty: 1, NoAddressNoMin: 2, NoAddress: 3, NoContent: 4, NoParts: 5, NoValidTypes: 6, InvalidTypes: 7 }; function validateMapPlace(place) { if (typeof place === "undefined" || !place) return validateMapPlaceResult.Empty; if (!place.hasOwnProperty("formatted_address") || typeof place.formatted_address !== "string") return place.name.length < 8 ? validateMapPlaceResult.NoAddressNoMin : validateMapPlaceResult.NoAddress; if (place.formatted_address.length == 0) return validateMapPlaceResult.NoContent; const address = place.formatted_address.split(','); if (address.length == 0) return validateMapPlaceResult.NoParts; const typesToRemove = [ "locality", "political" ]; const types = typeof place.types !== "undefined" && place.types ? place.types.filter( function( el ) { return !typesToRemove.includes( el ); } ) : []; if (types.length == 0) return validateMapPlaceResult.NoValidTypes; if (!(types.includes("street_address") || types.includes("premise") || types.includes("subpremise") || types.includes("point_of_interest") || types.includes("establishment"))) return validateMapPlaceResult.InvalidTypes; return validateMapPlaceResult.Ok; } function autocompleteAction(event, invalid, place = null) { if (autocomplete) { if (place) { if (typeof place === "string") place = JSON.parse(place); if (place.hasOwnProperty("results") && place.results.length > 0) place = place.results[0]; } if (!place) place = autocomplete.getPlace(); const valid = validateMapPlace(place); if (valid != validateMapPlaceResult.Ok) return invalid ? invalid(valid != validateMapPlaceResult.NoAddress) : null; event(place); } } function initMapAutocompleteInt(element, event, invalid = null) { var input = document.getElementById(element); var noResultsMessage = document.getElementById("mensaje_direccion"); // Aquí obtenemos el mensaje específico if (input) { let options = {}; if (countryCode) { options = { componentRestrictions: { country: countryCode } }; } autocomplete = new google.maps.places.Autocomplete(input, options); /*var autocompleteService = new google.maps.places.AutocompleteService(input, options);*/ var inPlaceChanged = false; var inChanged = false; google.maps.event.addListener(autocomplete, 'place_changed', function() { inPlaceChanged = true; inChanged = true; autocompleteAction(event, invalid); }); input.addEventListener('change', function() { inChanged = true; if (!inPlaceChanged) autocompleteAction(event, invalid); inPlaceChanged = false; }); input.addEventListener('blur', function() { if (!inChanged) autocompleteAction(event, invalid); inChanged = false; }); // Muestra u oculta el mensaje de "No tengo resultados" solo si el elemento existe /*console.log('ANTES DE noRESUELTEMSANE'); if (noResultsMessage) { console.log('DESPUES DE noRESUELTEMSANE'); input.addEventListener("input", function() { var searchText = input.value; console.log('DENOTRO DE LISTENER DE noRESUELTEMSANE'); if (searchText.length > 2) { // Solo busca si el texto tiene más de 2 caracteres autocompleteService.getPlacePredictions({ input: searchText, componentRestrictions: { country: countryCode } }, function(predictions, status) { if (status === google.maps.places.PlacesServiceStatus.OK && predictions.length > 0) { noResultsMessage.style.display = "none"; // Oculta el mensaje si hay resultados } else { noResultsMessage.innerHTML = tags['geo_direccion_incorrecta']; // Muestra el mensaje de error noResultsMessage.style.display = "block"; // Asegúrate de que el mensaje sea visible } }); } else { noResultsMessage.style.display = "none"; // Oculta el mensaje si no hay texto o es corto } }); }*/ let clearInput = document.querySelector('#address_icon_search'); if (clearInput) { // Verifica que el elemento exista clearInput.addEventListener('click', function(e) { e.preventDefault(); input.value = ''; input.focus(); }); } return autocomplete; } } /* ciudad.js */ function buscarCobertura() { let data = { pais_id: paisId, jsonGoogleMaps: $("#full_json_geo").val() } //console.log('gggg1'); new AjaxRequest({ endpoint: "geo/getDatosCobertura", sendAjax: true, data: data }); } var showMapa=false; var hayOpciones=false; function geogetDatosCoberturaCallbackDone(json) { console.log(json); if (json.result ?? true) { $("#supplier_id").val(json.supplier_id); $("#turbo").val(json.turbo); $("#nivelEntrega").val(json.nivelEntrega); $("#zona_id").val(json.zona_id); $("#pre_set_direccion_estado").val(json.pre_set_direccion.estado); if (json.pre_set_direccion.estado == 'WARNING' && json.pre_set_direccion.mensaje!=='') { $("#mensaje_direccion").removeClass("hidden"); $("#mensaje_direccion").html(json.pre_set_direccion.mensaje); } else { $("#mensaje_direccion").addClass("hidden"); } $("#zona_selected_id").val(json.zona_id); //$('#modalGeoDireccion').modal('show'); claudio , saco. if (json.zona_id) { if (json.turbo == true) { console.log("Tenemos turbo!", "success"); } else if (json.supplier_id > 0) { console.log("No tenemos turbo, pero tenemos florista en zona!"); } else { console.log("No tenemos florista en zona!"); } } else { console.log("Upps! No tenemos cobertura para esa direccion", "danger"); } $("#btn_confirmar_direccion").removeClass("hidden"); } return; } var autocomplete; var autocompleteService; function initMapAutocomplete() { var input = document.getElementById('find_address'); if (input) { autocomplete = initMapAutocompleteInt('find_address', function(place) { buscarEnMapa(place); }); //google.maps.event.addDomListener(input, 'keydown', function(event) { input.addEventListener('keydown', function(event) { //$("#mensaje_direccion").addClass("hidden");// saco el mensaje. if (event.key === 'Enter') { event.preventDefault(); // Previene el comportamiento por defecto de enviar el formulario var place = autocomplete.getPlace(); let aux=$('#find_address').val(); let sonDistintos=false; if (place!==undefined && !aux.includes(place.name)) { sonDistintos=true; } if (place && typeof place == "object" && place.hasOwnProperty("geometry") && !sonDistintos ) { buscarEnMapa(place); } else { cambioDireccion(); } } }); } } // Inicializa el servicio de autocompletar de Google Places let $input = $("#find_address"); $input.on("input", function() { let searchText = $input.val(); if (countryCode) { options = { componentRestrictions: { country: countryCode } }; } if (searchText.length > 2) { // Espera al menos 3 caracteres antes de buscar $('#mapContainer').hide(); autocompleteService.getPlacePredictions({ input: searchText, componentRestrictions: { country: countryCode } }, function(predictions, status) { hayOpciones=false; if (status === google.maps.places.PlacesServiceStatus.OK && predictions.length > 0) { // Hay resultados: oculta el mensaje de "No tengo resultados" hayOpciones=true; $("#mensaje_direccion").addClass("hidden"); } else { // No hay resultados: muestra el mensaje de "No tengo resultados" $("#mensaje_direccion").html(tags['geo_direccion_incorrecta']); $("#mensaje_direccion").removeClass("hidden");console.log('geo_direccion_incorrecta linea 112'); } }); } else { // Si el texto es muy corto, oculta el mensaje $("#mensaje_direccion").addClass("hidden"); } }); function buscarEnMapa(place) { showMapa=true; // Crear un nuevo mapa en el contenedor #mapContainer $('#mapContainer').show(); var map = new google.maps.Map(document.getElementById('mapContainer'), { center: place.geometry.location, zoom: 15, mapTypeControl: false }); // Crear un marcador en la ubicación del lugar var marker = new google.maps.Marker({ position: place.geometry.location, map: map }); $("#domicilio").val(place.formatted_address).trigger('change'); place.address_components.forEach(function (json) { if (json.types.includes("postal_code")) $("#postal_code_selected").val(json.short_name).trigger('change'); }); $("#lng").val(place.geometry.location.lng).trigger('change'); $("#lat").val(place.geometry.location.lat).trigger('change'); $("#full_json_geo").val(JSON.stringify({results: [place]})).trigger('change'); buscarCobertura(); } $('#find_address').change(function () { $("#full_json_geo").val(); }); function cambioDireccion() { var place = autocomplete.getPlace(); console.log(place); let aux=$('#find_address').val(); if (place !== undefined && !aux.includes(place.name) && showMapa & place.place_id!== undefined ) { resetAutocomplete(aux);console.log('resetado2:'+aux);showMapa=false; } if (aux){ geocodeAddress(aux); } else { if (!showMapa){ $("#mensaje_direccion").removeClass("hidden"); if (hayOpciones) { $("#mensaje_direccion").html(tags['geo_direccion_mas_especifica']); console.log('geo_direccion_mas_especifica linea 193.1'); } else{ $("#mensaje_direccion").html(tags['geo_direccion_incorrecta']); console.log('geo_direccion_incorrecta linea 193.2'); } } } } $('#find_address').blur(function(event) { cambioDireccion(); }); $('#find_address').on('input', function() { $('#mapContainer').hide(); //$('#mensaje_direccion').addClass('hidden'); $('#mensaje_direccion').html('

'); $("#btn_confirmar_direccion").addClass("hidden"); }); function resetAutocomplete(valorInicial) { // Limpia el campo de entrada $('#find_address').val(valorInicial); // Limpia cualquier referencia previa al lugar seleccionado place = null; setTimeout(function() { $('#find_address').val(valorInicial); }, 500); } /* $('#find_address').keyup(function(event) { if (event.which === 13) { // 13 es el código de la tecla Enter //cambioDireccion(); } }); */ function geocodeAddress(address) { console.log('ADDRESS:' + address); geocoder = new google.maps.Geocoder(); geocoder.geocode({ 'address': address ,'componentRestrictions': { 'country': countryCode }}, function (results, status) { console.log(results); console.log(status); if (status === 'OK') { place = results[0]; console.log('linea 214'); if (validateMapPlace(place)/*|| true*/){ $("#mensaje_direccion").removeClass("hidden"); if (hayOpciones) { $("#mensaje_direccion").html(tags['geo_direccion_mas_especifica']); console.log('geo_direccion_mas_especifica linea 259.1'); } else{ $("#mensaje_direccion").html(tags['geo_direccion_incorrecta']); console.log('geo_direccion_incorrecta linea 259.2'); } return; } console.log('buscarmapa3'); buscarEnMapa(place); /* var location = results[0].geometry.location; //map.setCenter(location); var latlng = new google.maps.LatLng(location.lat(), location.lng()); var mapOptions = { zoom: 15, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById('mapContainer'), mapOptions); map.setCenter(latlng); var marker = new google.maps.Marker({ map: map, draggable: true }); //map.setCenter(new google.maps.LatLng(location.lat(), location.lng())); marker.setPosition(location); let aux = getPath(results[0]); alert('full'); alert(aux.fullAddress); $("#domicilio").val(aux.fullAddress).trigger('change'); $("#postal_code_selected").val(aux.postal_code_selected).trigger('change'); $("#lng").val(aux.lng).trigger('change'); $("#lat").val(aux.lat).trigger('change'); $("#full_json_geo").val(aux.fullJson).trigger('change'); buscarCobertura(); //$('#lat').val(location.lat()); //$('#lng').val(location.lng()); */ } else { console.log('Geocode was not successful for the following reason: ' + status); $("#mensaje_direccion").html(tags['geo_direccion_incorrecta']); $("#mensaje_direccion").removeClass("hidden");console.log('geo_direccion_incorrecta linea 296'); } }); //alert('2'); //buscarCobertura(); } $('#domicilio').on('focus', function () { // Código que se ejecuta cuando el campo domicilio empieza a ser editado $("#domicilio_control").removeClass("glyphicon-pencil"); $("#domicilio_control").addClass('glyphicon-ok'); // Aquí puedes agregar el código que necesites ejecutar cuando el campo domicilio reciba el foco }); $('#domicilio_control').on('click', function () { $('#modalGeoDireccion').modal('hide'); //$('#dropdown_localizar').modal('show'); /* $("#domicilio_control").removeClass("glyphicon-ok"); $("#domicilio_control").addClass('glyphicon-pencil'); var address = $('domicilio').val(); if (address) { buscarCobertura(); }*/ }); $('#domicilio').on('blur', function () { $("#domicilio_control").removeClass("glyphicon-ok"); $("#domicilio_control").addClass('glyphicon-pencil'); var address = $(this).val();console.log('address:'+address); if (address) { console.log('address2:'+address); geocodeAddress(address); } }); function setDireccion(forzar_cambio_zona = false) { let data = { direccion: $("#domicilio").val(), codigo_postal: $("#postal_code_selected").val(), lng: $("#lng").val(), lat: $("#lat").val(), supplier_id: $("#supplier_id").val(), zona_selected_id: $("#zona_selected_id").val(), turbo: $("#turbo").val(), nivelEntrega: $("#nivelEntrega").val(), full_json_geo: $("#full_json_geo").val(), pageName: page, central_obj_id: centralObjId, forzar_cambio_zona: forzar_cambio_zona || $("#pre_set_direccion_estado").val() == 'WARNING' } new AjaxRequest({ endpoint: "carrito/setDireccion", data: data }); } $("#btn_confirmar_direccion").click(function () { setDireccion(); }); function carritosetDireccionCallbackDone(json, extraData, data) { console.log(json); /*.* Por ahora, mostarmos el warning y forzamos cambio de zona if ($("#pre_set_direccion_estado").val() == 'si') { // si $('#modalGeoDireccion').modal('hide'); dataFechas(true, true).always(function () { reloadDates(); $('#modalCalendar').modal('show'); animateAlert($("#modalCalendar").data("alert")); }); if (json.hasOwnProperty("url")) urlCalendarCallback = json.url; } else *.*/{ if (json.hasOwnProperty("url")) { window.location.href = json.url; } else if (typeof dataFechas === "function") { dataFechas(); } } actualizoADondeEnviar(data.direccion); actualizoNivelHorario(data.nivelEntrega); } $(document).on("click", "#modalChangeCityAddress .cambiar_zona", function(e){ e.preventDefault(); setDireccion(true); }); //lo pongo en ciudad pero despues veo donde tiene que ir porque tiene que depender de header. //VER PORQUE NO ANDA ESTO $(document).ready(function () { // Maneja el evento de clic para el primer botón $('.dropdownLocalizar').on('click', function (e) { e.preventDefault(); //$('#dropdown_localizar').toggle(); $('.pac-container').appendTo('#dropdown_localizar'); //$('.pac-container').appendTo('#modalGeoDireccion');} $('#dropdown_localizar').modal('show'); $('#domicilio').val($('#find_address').val()); //$('#dropdown_localizar').modal('show'); //.modal('hide'); }); /* // Opcional: Cierra el menú si se hace clic fuera de él $(document).on('click', function (e) { if (!$(e.target).closest('#dropdownLocalizar1, #dropdownLocalizar2, #dropdown_localizar').length) { //e.preventDefault(); // Prevenir comportamiento inesperado //alert('cierro3'); //console.log(e.target); //$('#dropdown_localizar').hide(); } }); */ });