added dynamic filters

master
Gustavo Luigi 2023-06-20 15:34:36 -03:00
parent 89770328b9
commit a3d1f45e5f
6 changed files with 377 additions and 217 deletions

18
assets/content/script.js Normal file
View File

@ -0,0 +1,18 @@
function initMap() {

const map = new google.maps.Map(document.getElementById("map"), {
zoom: 8,
center: { lat: parseFloat(item.location.lat), lng: parseFloat(item.location.lng) },
streetViewControl: false,
mapTypeControl: false,
fullscreenControl: false,
});

new google.maps.Marker({
position: { lat: parseFloat(item.location.lat), lng: parseFloat(item.location.lng) },
map: map,
title: item.title,
optimized: false,
});
}
window.initMap = initMap;

306
assets/home/script.js Normal file
View File

@ -0,0 +1,306 @@
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.removeClass('d-none');
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);
});

}

View File

Before

Width:  |  Height:  |  Size: 8.1 KiB

After

Width:  |  Height:  |  Size: 8.1 KiB

View File

@ -34,27 +34,8 @@
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAKGJCCKvmWZl-L5bBF0uS5BWf0gN4ZkpI&callback=initMap&v=weekly" defer></script>
<script>
const contentUrl = "{{url('/api/contents/'.$content->id)}}";
const locationField = "{{config('settings.location_field')}}";
</script>
<script>
function initMap() {
let item = {!! json_encode($content) !!};
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 8,
center: { lat: parseFloat(item.location.lat), lng: parseFloat(item.location.lng) },
streetViewControl: false,
mapTypeControl: false,
fullscreenControl: false,
});

let marker = new google.maps.Marker({
position: { lat: parseFloat(item.location.lat), lng: parseFloat(item.location.lng) },
map: map,
title: item.title,
optimized: false,
});
}
window.initMap = initMap;
const locationField = "{{$_location_field}}";
let item = {!! json_encode($content)!!};
</script>
<script src="{{storage('assets/content/script.js')}}"></script>
@stop

View File

@ -49,48 +49,69 @@
</div>
</div>
<div class="row mb-3">
<div id="filters" class="col-12 col-md rounded-end">
<div class="col-12 col-md rounded-end">
<div class="d-flex">
<div id="filters">
<div class="dropdown me-2 d-none">
<button class="btn btn-primary dropdown-toggle btn-sm" style="color: #212529; background: #e9ecef; border: 1px solid #ced4da;" type="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
$filter <span class="caret"></span>
</button>
<ul class="dropdown-menu checkbox-menu allow-focus p-2" id="options">
<li>
<label>
<input class="check-filter" type="checkbox" value="1"> $option
</label>
</li>
</ul>
</div>
<div id="filters" class="d-flex">
<template id="filter">
<div class="dropdown me-2 filter">
<button class="btn btn-primary dropdown-toggle btn-sm bg-light" style="color: #212529; background: #e9ecef; border: 1px solid #ced4da;" type="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
<span class="filter-name"></span> <span class="caret"></span>
</button>
<ul class="dropdown-menu checkbox-menu allow-focus p-2 filter-options"></ul>
</div>
</template>
</div>
<div style="width: 350px;">
<div class="flex-fill me-2" style="max-width: 400px;">
<input type="text" class="form-control form-control-sm" id="ort" placeholder="Ort"/>
</div>
<div style="width: 250px;" class="input-group ms-2">
<div class="input-group flex-fill me-2" style="max-width: 400px;">
<input type="text" class="form-control form-control-sm" id="search-input" placeholder="Freitext-Suche">
<span class="input-group-text" id="search-button">
<button class="input-group-text bg-primary text-light" id="search-button">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-search" viewBox="0 0 16 16">
<path d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z"/>
</svg>
</span>
</button>
</div>
</div>
<div class="mt-2 d-flex">
<div class="d-flex">
<div id="applied-filters" class="d-flex">
<template id="applied-filter">
<button class="btn btn-sm btn-primary me-2 btn applied-filter d-none">
<span class="filter-name"></span>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-x" viewBox="0 0 16 16">
<path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"/>
</svg>
</button>
</template>
</div>
<button class="btn btn-sm btn-primary me-2 btn applied-filter" data-field="ort" style="display: none;">
<span class="filter-name"></span>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-x" viewBox="0 0 16 16">
<path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"/>
</svg>
</button>
<button class="btn btn-sm btn-primary me-2 btn applied-filter" data-field="search" style="display: none;">
<span class="filter-name"></span>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-x" viewBox="0 0 16 16">
<path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"/>
</svg>
</button>
</div>
<button id="reset-filters-button" class="btn btn-danger btn-sm ms-1" style="display: none;">Alle löschen</button>
</div>
</div>
<div class="col-12 col-md-auto pe-0 d-flex align-items-end">
<p class="text-end text-muted small m-0 p-0"><span id="count-items-displayed">0</span> results</p>
</div>
</div>
<div class="row">

<div class="col-12 col-md-8 g-0 ps-md-3 order-md-last">
<div id="map"></div>
<div id="marker-window" class="d-none">
<h6 id="firstHeading" class="firstHeading">$title</h6>
<div id="bodyContent">
<img class="img-fluid rounded" data-src="$image" alt="">

<p>$description</p>
<a data-href="$path" style="outline: none;">Details</a>
</div>
@ -111,186 +132,15 @@
</div>
</div>
</div>

</div>
</div>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<script>
const contentUrl = "{{url('/types/'.$_type.'/contents')}}";
const urlBase = "{{url('/')}}";
const type = "{{$_type}}";
const locationField = "{{$_location_field}}";
//const filterFields = ['categoria'];
</script>
<script>
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(contentUrl).done(function (contents) {
let items = contents["contents"];
if (items != undefined) {
locationItems = items.filter(function (item) { return item[locationField].lat !== '' && item[locationField].lng !== '' });
currentItems = locationItems;
loadCurrentItems();
}
});

let markerCluster;

function loadCurrentItems() {
$("#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[locationField].lat);
item.location.lng = parseFloat(item[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: '/template/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.removeClass('d-none');
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 () {
$("#contents").html("");
let value = $("#search-input").val();
currentItems = locationItems.filter(function (item) {
return item.title.toLowerCase().includes(value.toLowerCase());
});
loadCurrentItems();
});

function setLocationFocus(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();
});

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);
});

}
let filterFields = {!! json_encode($_filter_fields) !!};
</script>
<script src="{{storage('assets/home/script.js')}}"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAKGJCCKvmWZl-L5bBF0uS5BWf0gN4ZkpI&libraries=places&callback=initMap"></script>
@stop

View File

@ -10,5 +10,10 @@
"value": "Address",
"type": "string",
"required": true
},
{
"name": "Filter Fields",
"type": "array",
"required": true
}
]