maps-theme/assets/home/script.js

312 lines
13 KiB
JavaScript

function textToSlug(text) {
return text.toString().toLowerCase()
.normalize('NFD').replace(/[\u0300-\u036f]/g, '')
.replace(/\s+/g, '-')
.replace(/[^\w\-]+/g, '')
.replace(/\-\-+/g, '-')
.replace(/^-+/, '')
.replace(/-+$/, '');
}
let selectFields = {};
$(function () {
$.get(urlBase + "/types/" + textToSlug(type) + "/fields").done(function (response) {
let allField = response["fields"];
allField.forEach(function (field) {
if (field.type == "select") selectFields[field.name] = field.attr.tags;
});
filterFields.forEach(function (item) {
let filterTemplate = $('#filter');
let filterElement = $(filterTemplate.clone().html());
filterElement.find('.filter-name').text(item);
let options = selectFields[item];
options.forEach(function (option) {
let filterOption = `
<li>
<label onclick="event.stopPropagation()">
<input class="check-filter me-1" data-field="${item}" type="checkbox" name="filter-options" value="${option}">${option}
</label>
</li>`;
filterElement.find('.filter-options').append(filterOption);
});
$('#filters').append(filterElement);
let appliedFilterTemplate = $('#applied-filter');
let appliedFilterElement = $(appliedFilterTemplate.clone().html());
appliedFilterElement.find('.filter-name').text(item);
appliedFilterElement.attr('data-field', item);
$('#applied-filters').append(appliedFilterElement);
});
});
});
function initMap() {
function createInfowindowElement(item) {
let infowindowElement = $("#marker-window").clone();
infowindowElement.html(infowindowElement.html().replace('$title', item.title));
infowindowElement.html(infowindowElement.html().replace('$description', item.description ?? ''));
infowindowElement.html(infowindowElement.html().replace('data-href="$path"', 'href="' + item.path + '"'));
infowindowElement.removeClass('d-none');
return infowindowElement[0].outerHTML;
}
let map = new google.maps.Map(document.getElementById("map"), {
streetViewControl: false,
mapTypeControl: false,
fullscreenControl: false,
});
let currentItems = [];
$.get(urlBase + "/types/" + textToSlug(type) + "/contents").done(function (contents) {
let items = contents["contents"];
if (items != undefined) {
locationItems = items.filter(function (item) { return item[textToSlug(locationField)].lat !== '' && item[textToSlug(locationField)].lng !== '' });
currentItems = locationItems;
loadCurrentItems();
}
});
let markerCluster;
function loadCurrentItems() {
applyFilters();
$("#count-items-displayed").text(currentItems.length);
if (markerCluster != undefined) markerCluster.clearMarkers();
if (currentItems.length > 0) {
let openInfoWindow = null;
currentItems = currentItems.map(function (item) {
if (item.location == undefined) item.location = {};
item.location.lat = parseFloat(item[textToSlug(locationField)].lat);
item.location.lng = parseFloat(item[textToSlug(locationField)].lng);
let marker = new google.maps.Marker({
position: { lat: item.location.lat, lng: item.location.lng },
map: map,
title: item.title,
optimized: false,
});
let infowindowElement = createInfowindowElement(item);
let infowindow = new google.maps.InfoWindow({ content: infowindowElement });
marker.addListener('click', function () {
if (openInfoWindow) openInfoWindow.close();
infowindow.open({ anchor: marker, map });
openInfoWindow = infowindow;
});
item.marker = marker;
return item;
});
let markers = currentItems.map(item => item.marker);
markerCluster = new MarkerClusterer(map, markers);
markerCluster.setStyles([{
url: urlBase + '/template/assets/images/cluster.png',
height: 40,
width: 40,
textSize: 14,
backgroundPosition: '0 0',
iconAnchor: [26, 53],
textColor: '#ffffff'
}]);
setTimeout(() => {
clearFocus();
showVisibleMarkers();
}, 100);
}
}
const locationElementTemplate = $("#contents").children().first();
locationElementTemplate.remove();
function showVisibleMarkers() {
let showedItems = currentItems.filter(function (item) {
return map.getBounds().contains(item.marker.getPosition());
});
$("#count-items-displayed").text(showedItems.length);
$("#contents").empty();
showedItems.forEach(function (item) {
let locationElement = locationElementTemplate.clone();
locationElement.html(locationElement.html().replace('$title', item.title));
locationElement.html(locationElement.html().replace('data-src="$image"', 'src="' + item.image + '"'));
locationElement.html(locationElement.html().replace('data-href="$path"', 'href="' + item.path + '"'));
locationElement.html(locationElement.html().replace('$postalCode', (item[textToSlug(locationField)].postalCode + " " + (item[textToSlug(locationField)].addressLocality ?? "")).trim()));
locationElement.removeClass('d-none');
if (item[textToSlug(tagField)]) item[textToSlug(tagField)].slice(0, 2).forEach(function (besonderheitenItem) {
locationElement.find(".tags").append(`<span class="badge text-bg-secondary">${besonderheitenItem}</span>`);
});
locationElement.on('click', function () {
map.setZoom(12);
map.setCenter(item.marker.getPosition());
showVisibleMarkers();
google.maps.event.trigger(item.marker, 'click');
});
$("#contents").append(locationElement);
});
showedItems = currentItems;
}
google.maps.event.addListener(map, 'dragend', showVisibleMarkers);
google.maps.event.addListener(map, 'zoom_changed', showVisibleMarkers);
$("#search-input").on("keyup", function (event) {
if (event.key === "Enter") $("#search-button").click();
});
$("#search-button").on("click", function () {
if ($("#search-input").val() === "") {
$(".applied-filter[data-field='search']").addClass("d-none").removeClass("d-inline-block");
$(".applied-filter[data-field='search']").find(".filter-name").text("");
}
else {
$(".applied-filter[data-field='search']").removeClass("d-none").addClass("d-inline-block");
$(".applied-filter[data-field='search']").find(".filter-name").text("Freitext: " + $("#search-input").val());
}
let selectedFilterOptions = $(".check-filter[name='filter-options']:checked").length;
if (selectedFilterOptions > 0 || $("#ort").val() != "" || $("#search-input").val() != "") $("#reset-filters-button").show();
else $("#reset-filters-button").hide();
loadCurrentItems();
});
$(document).on("click", ".applied-filter", function () {
let field = $(this).attr("data-field");
if (field == "ort") $("#ort").val("");
else if (field == "search") $("#search-input").val("");
else {
$(".check-filter[data-field='" + field + "'][name='filter-options']:checked").prop("checked", false);
$(".check-filter[data-field='" + field + "'][name='filter-options']").trigger("change");
}
});
$(document).on("change", ".check-filter", function () {
loadCurrentItems();
});
function applyFilters() {
let searchedValue = $("#search-input").val();
currentItems = locationItems.filter(function (item) {
return item.title.toLowerCase().includes(searchedValue.toLowerCase());
});
Object.keys(selectFields).forEach(function (name) {
let key = textToSlug(name);
let locationWithSelectField = currentItems.filter(function (item) {
return item[key] != undefined;
});
let selectedOptions = $(".check-filter[data-field='" + name + "'][name='filter-options']:checked").map(function () {
return $(this).val();
}).get();
if (selectedOptions.length > 0) {
if (selectedOptions.length > 0) {
$(".applied-filter[data-field='" + name + "']").removeClass("d-none").addClass("d-inline-block");
$(".applied-filter[data-field='" + name + "']").find(".filter-name").text(name + ": " + selectedOptions.join(", "));
}
currentItems = locationWithSelectField.filter(function (item) {
return selectedOptions.some(function (selectedOption) {
return item[key].includes(selectedOption);
});
});
} else {
$(".applied-filter[data-field='" + name + "']").removeClass("d-inline-block").addClass("d-none");
$(".applied-filter[data-field='" + name + "']").find(".filter-name").text(name);
}
});
let selectedFilterOptions = $(".check-filter[name='filter-options']:checked").length;
if (selectedFilterOptions > 0 || $("#ort").val() != "" || $("#search-input").val() != "") $("#reset-filters-button").show();
else $("#reset-filters-button").hide();
}
$("#reset-filters-button").click(function () {
$("#search-input").val("");
$("#search-button").trigger("click");
$("#ort").val("");
$("#ort").trigger("change");
$(".check-filter").prop("checked", false);
$(".check-filter").trigger('change');
loadCurrentItems();
});
function setLocationFocus(address) {
$(".applied-filter[data-field='ort']").show();
$(".applied-filter[data-field='ort']").find(".filter-name").text("Ort: " + address);
new google.maps.Geocoder().geocode({ 'address': address }, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
map.fitBounds(results[0].geometry.viewport);
} else {
console.warn('Geocode não obteve sucesso devido a: ' + status);
}
});
}
function clearFocus() {
let markers = currentItems.map(item => item.marker);
if (currentItems.length == 1) {
map.setZoom(12);
map.setCenter(markers[0].getPosition());
} else {
let bounds = new google.maps.LatLngBounds();
markers.forEach(function (marker) {
bounds.extend(marker.getPosition());
});
map.fitBounds(bounds);
}
}
$('#ort').on("change", function () {
if ($(this).val() === "") {
clearFocus();
$(".applied-filter[data-field='ort']").hide();
$(".applied-filter[data-field='ort']").find(".filter-name").text("");
}
let selectedFilterOptions = $(".check-filter[name='filter-options']:checked").length;
if (selectedFilterOptions > 0 || $("#ort").val() != "" || $("#search-input").val() != "") $("#reset-filters-button").show();
else $("#reset-filters-button").hide();
});
let locationInput = $('#ort')[0];
let autocomplete = new google.maps.places.Autocomplete(locationInput, { "types": ["country", "route", "street_address", "locality"], "componentRestrictions": { "country": ["de", "se", "at", "nl", "br"] } });
autocomplete.addListener("place_changed", function () {
let place = autocomplete.getPlace();
let address = place.formatted_address;
if (!place.geometry) {
let inputText = locationInput.value;
let autocompleteService = new google.maps.places.AutocompleteService();
autocompleteService.getPlacePredictions({ input: inputText, componentRestrictions: { country: ["de", "se", "at", "nl", "br"] } }, function (predictions, status) {
if (status === google.maps.places.PlacesServiceStatus.OK && predictions && predictions.length > 0) {
let firstPrediction = predictions[0];
address = firstPrediction.description;
locationInput.value = address;
setLocationFocus(address);
}
});
} else setLocationFocus(address);
});
}