Non puoi selezionare più di 25 argomenti
Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
622 righe
32 KiB
622 righe
32 KiB
<?= $this->element('./MapCore/MapPrimitives') ?> |
|
<?php |
|
use Cake\Core\Configure; |
|
use Cake\I18n\I18n; |
|
|
|
// recupero configurazioni mappa |
|
$map_config = Configure::read('App.mapConfig'); |
|
$upperLeftBoundLon = $map_config['upperLeftBoundLon']; |
|
$upperLeftBoundLat = $map_config['upperLeftBoundLat']; |
|
$lowerRightBoundLon = $map_config['lowerRightBoundLon']; |
|
$lowerRightBoundLat = $map_config['lowerRightBoundLat']; |
|
$config_center_lat = $map_config['center_lat']; |
|
$config_center_lon = $map_config['center_lon']; |
|
$config_center_zoom = $map_config['center_zoom']; |
|
$min_zoom_level = $map_config['min_zoom_level']; |
|
?> |
|
<script type="text/javascript"> |
|
var configJS = {}; |
|
|
|
configJS.geoserverUrl = '<?= Configure::read('App.geoserverUrl') ?>'; |
|
configJS.geoserverAPP = '<?= Configure::read('App.geoserverAPP') ?>'; |
|
configJS.tilesServerUrl = '<?= Configure::read('App.tilesServerUrl') ?>'; |
|
configJS.checkOfflineThreshold = '<?= Configure::read('App.checkOfflineThreshold') ?>'; |
|
configJS.lastCheckOffline = '<?= Configure::read('App.lastCheckOffline') ?>'; |
|
configJS.offlineThreshold = '<?= Configure::read('App.offlineThreshold') ?>'; |
|
configJS.tileCheckTimeout = '<?= Configure::read('App.tileCheckTimeout') ?>'; |
|
configJS.maxTilesQueueElements = '<?= Configure::read('App.maxTilesQueueElements') ?>'; |
|
configJS.enableGoogleMapsLayers = '<?= Configure::read('App.enableGoogleMapsLayers') ?>'; |
|
configJS.enableOSMOffline = '<?= Configure::read('App.enableOSMOffline') ?>'; |
|
configJS.enableOSMOnline = '<?= Configure::read('App.enableOSMOnline') ?>'; |
|
configJS.locale = '<?= I18n::getLocale() ?>'; |
|
|
|
|
|
// creazione oggetto di interazione mappa di tipo select |
|
var selectInteraction = new ol.interaction.Select({ |
|
style: selectedStyleFunctionGenerator(), |
|
}); |
|
|
|
// gestione del popup: |
|
var popup_container = document.getElementById('jixel-popup'); |
|
var popup_header = document.getElementById('jixel-popup-header'); |
|
var popup_content = document.getElementById('jixel-popup-content'); |
|
var popup_closer = document.getElementById('jixel-popup-closer'); |
|
|
|
var popupOverlay = new ol.Overlay({ |
|
element: popup_container, |
|
autoPan: true, |
|
autoPanAnimation: { |
|
duration: 500 |
|
} |
|
}); |
|
|
|
popup_closer.onclick = (evt) => { |
|
selectInteraction.getFeatures().clear(); |
|
popupOverlay.setPosition(undefined); |
|
popup_closer.blur(); |
|
return false; |
|
}; |
|
|
|
// gestione popup al select/unselect feature |
|
selectInteraction.on('select', (evt) => { |
|
console.log(evt); |
|
if (evt.selected.length > 0) { |
|
const selected_layer = evt.target.getLayer(evt.selected[0]); |
|
if (!selected_layer || !selected_layer.get('code')) return; |
|
const selected_layer_vector_source = selected_layer.get('clusterized') ? selected_layer.getSource().getSource() : selected_layer.getSource(); |
|
const describe_feature_properties = selected_layer_vector_source.describe_feature_properties; |
|
let header = '<b>' + selected_layer.get('name') + '</b><hr>'; |
|
let body = ''; |
|
evt.selected.forEach((selected_feature) => { |
|
if (selected_feature.get('features') == undefined) { |
|
body += generatePopupEntryFromFeature(selected_feature, describe_feature_properties); |
|
} else { |
|
selected_feature.get('features').forEach((feature) => { |
|
body += generatePopupEntryFromFeature(feature, describe_feature_properties); |
|
}); |
|
} |
|
}); |
|
let coordinate = evt.mapBrowserEvent.coordinate; |
|
popup_header.innerHTML = header; |
|
popup_content.innerHTML = body; |
|
popupOverlay.setPosition(coordinate); |
|
} else { |
|
popupOverlay.setPosition(undefined); |
|
popup_closer.blur(); |
|
} |
|
}); |
|
|
|
// array di tutti i layers da aggiungere alla mappa: |
|
var map_layers = []; |
|
|
|
// array di tutti i layers di base da aggiungere alla mappa: |
|
var base_layers = []; |
|
|
|
// istanziamo il notification object: |
|
var ol_notification = new ol.control.Notification(); |
|
|
|
// sezione gestione layer OSM online e/o offline |
|
if (configJS.enableOSMOnline || configJS.enableOSMOffline) { |
|
const osm_online_source = new ol.source.OSM({attributions: 'ONLINE'}); |
|
const osm_offline_source = new ol.source.OSM({attributions: 'OFFLINE', url: configJS.tilesServerUrl + "${z}/${x}/${y}.png",crossOrigin: null,}); |
|
const osm_layer_source = configJS.enableOSMOnline ? osm_online_source : osm_offline_source; |
|
|
|
// Tile layer di base (OSM): |
|
const osmLayer = new ol.layer.Tile({ |
|
name: configJS.enableOSMOnline ? '<?= __('OpenStreetMap ONLINE') ?>' : '<?= __('OpenStreetMap OFFLINE') ?>', |
|
source: osm_layer_source, |
|
}); |
|
base_layers.push(osmLayer); |
|
|
|
if (configJS.enableOSMOnline && configJS.enableOSMOffline) { |
|
var osm_online = true; |
|
let last_osm_check = Math.floor(Date.now() / 1000); |
|
|
|
const switch_osm_online = () => { |
|
console.log("OSM switching back online..."); |
|
ol_notification.show('<?= __('OpenStreetMap ONLINE') ?>') |
|
osm_online = true; |
|
last_osm_check = Math.floor(Date.now() / 1000); |
|
osmLayer.setSource(osm_online_source); |
|
osmLayer.set('name', '<?= __('OpenStreetMap ONLINE') ?>'); |
|
}; |
|
|
|
const switch_osm_offline = () => { |
|
console.log("OSM switching offline..."); |
|
ol_notification.show('<?= __('OpenStreetMap OFFLINE') ?>') |
|
osm_online = false; |
|
last_osm_check = Math.floor(Date.now() / 1000); |
|
osmLayer.setSource(osm_offline_source); |
|
osmLayer.set('name', '<?= __('OpenStreetMap OFFLINE') ?>'); |
|
}; |
|
|
|
var checkOSM = () => { |
|
console.log("checkOSM"); |
|
if (osm_online) { |
|
last_osm_check = Math.floor(Date.now() / 1000); |
|
console.log("checkOSM already online. Updating timestamp to: " + last_osm_check); |
|
return; |
|
} |
|
if (Math.floor(Date.now() / 1000) - last_osm_check > configJS.checkOfflineThreshold) { |
|
switch_osm_online(); |
|
} |
|
}; |
|
|
|
osm_layer_source.setTileLoadFunction(function(tile, src) { |
|
var xhr = new XMLHttpRequest(); |
|
xhr.timeout = configJS.tileCheckTimeout; |
|
xhr.responseType = 'blob'; |
|
xhr.ontimeout = function () { |
|
console.error("TileLoadFunction load timed out."); |
|
tile.setState(3); // set tile status ERROR |
|
switch_osm_offline(); |
|
}; |
|
xhr.addEventListener('loadend', function (evt) { |
|
if (this.response instanceof Blob) { |
|
tile.getImage().src = URL.createObjectURL(this.response); |
|
} else { |
|
console.log("TileLoadFunction data error!"); |
|
tile.setState(3); // set tile status ERROR |
|
switch_osm_offline(); |
|
} |
|
}); |
|
xhr.addEventListener('error', function () { |
|
console.log("TileLoadFunction load error!"); |
|
tile.setState(3); // set tile status ERROR |
|
switch_osm_offline(); |
|
}); |
|
xhr.open('GET', src); |
|
xhr.send(); |
|
}); |
|
} |
|
} |
|
|
|
// sezione gestione layers GoogleMaps |
|
if (configJS.enableGoogleMapsLayers) { |
|
const googleLayerRoadNames = new ol.layer.Tile({ |
|
visible: false, |
|
title: "Google Road Names", |
|
source: new ol.source.TileImage({ url: 'https://mt1.google.com/vt/lyrs=h&x={x}&y={y}&z={z}' }), |
|
}); |
|
base_layers.push(googleLayerRoadNames); |
|
|
|
const googleLayerRoadmap = new ol.layer.Tile({ |
|
visible: false, |
|
title: "Google Road Map", |
|
source: new ol.source.TileImage({ url: 'https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}' }), |
|
}); |
|
base_layers.push(googleLayerRoadmap); |
|
|
|
const googleLayerSatellite = new ol.layer.Tile({ |
|
visible: false, |
|
title: "Google Satellite", |
|
source: new ol.source.TileImage({ url: 'https://mt1.google.com/vt/lyrs=s&hl=pl&&x={x}&y={y}&z={z}' }), |
|
}); |
|
base_layers.push(googleLayerSatellite); |
|
|
|
const googleLayerHybrid = new ol.layer.Tile({ |
|
visible: !(configJS.enableOSMOnline || configJS.enableOSMOffline), |
|
title: "Google Satellite & Roads", |
|
source: new ol.source.TileImage({ url: 'https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}' }), |
|
}); |
|
base_layers.push(googleLayerHybrid); |
|
|
|
const googleLayerTerrain = new ol.layer.Tile({ |
|
visible: false, |
|
title: "Google Terrain", |
|
source: new ol.source.TileImage({ url: 'https://mt1.google.com/vt/lyrs=t&x={x}&y={y}&z={z}' }), |
|
}); |
|
base_layers.push(googleLayerTerrain); |
|
|
|
const googleLayerHybrid2 = new ol.layer.Tile({ |
|
visible: false, |
|
title: "Google Terrain & Roads", |
|
source: new ol.source.TileImage({ url: 'https://mt1.google.com/vt/lyrs=p&x={x}&y={y}&z={z}' }), |
|
}); |
|
base_layers.push(googleLayerHybrid2); |
|
|
|
const googleLayerOnlyRoad = new ol.layer.Tile({ |
|
visible: false, |
|
title: "Google Road without Building", |
|
source: new ol.source.TileImage({ url: 'https://mt1.google.com/vt/lyrs=r&x={x}&y={y}&z={z}' }), |
|
}); |
|
base_layers.push(googleLayerOnlyRoad); |
|
} |
|
|
|
if (base_layers.length > 0) { |
|
// se config prevede almeno un layer di base, creiamo il gruppo e lo aggiungiamo ai layers della mappa: |
|
const base_layers_group = new ol.layer.Group({ |
|
title: 'Base Layers', |
|
openInLayerSwitcher: false, // il gruppo sul layerSwitcher sarà chiuso di default |
|
layers: base_layers, |
|
}); |
|
map_layers.push(base_layers_group); |
|
} |
|
|
|
// recupero i layers dall'option 'layers' ricevuto |
|
var layers = JSON.parse('<?= json_encode($layers) ?>'); |
|
|
|
// creazione e configurazione di tutti i layers |
|
layers.forEach((layer_info) => { |
|
map_layers.push(createLayer(layer_info)); |
|
}); |
|
|
|
let controls = [ |
|
new ol.control.LayerSwitcher(), |
|
ol_notification, |
|
]; |
|
|
|
<?php if ($tools): ?> |
|
const toolsButtonElement = document.getElementById('jixel-tools-element'); |
|
const toolsControl = new ol.control.Control({element: toolsButtonElement}); |
|
const geo_resources = '<?= $geo_resources !== false ? json_encode($geo_resources) : '' ?>'; |
|
const geo_resources_mapped_fields = JSON.parse('<?= json_encode(collection($geo_resources !== false ? $geo_resources : [])->reduce(function ($acc, $geo_resource) { return array_merge($acc, array_values($geo_resource['attributes_fields'])); }, [])) ?>'); |
|
controls.push(toolsControl); |
|
<?php if ($geocoding): ?> |
|
let results = null; |
|
|
|
function empty_fields_from_geo_resources(geo_resources_mapped_fields) { |
|
geo_resources_mapped_fields.forEach(field_id => { |
|
if (document.getElementById(field_id)) { |
|
document.getElementById(field_id).value = ''; |
|
} |
|
}); |
|
} |
|
|
|
function fill_fields_from_geo_resources(mapped_fields) { |
|
Object.keys(mapped_fields).forEach(field_id => { |
|
console.log(`trying to fill field with id "${field_id}" with value "${mapped_fields[field_id]}"...`); |
|
if (document.getElementById(field_id)) { |
|
document.getElementById(field_id).value = mapped_fields[field_id]; |
|
console.log(`"${field_id}" = "${mapped_fields[field_id]}" SUCCEDED!`); |
|
} |
|
}); |
|
} |
|
|
|
function geocodeWithCoordinates(coordinates) { |
|
if (document.getElementById('<?= $cap_id ?>')) document.getElementById('<?= $cap_id ?>').value = ''; |
|
if (document.getElementById('<?= $province_id ?>')) document.getElementById('<?= $province_id ?>').value = ''; |
|
if (document.getElementById('<?= $district_code_id ?>')) document.getElementById('<?= $district_code_id ?>').value = ''; |
|
if (document.getElementById('<?= $district_id ?>')) document.getElementById('<?= $district_id ?>').value = ''; |
|
if (document.getElementById('<?= $address_id ?>')) document.getElementById('<?= $address_id ?>').value = ''; |
|
if (document.getElementById('<?= $description_id ?>')) document.getElementById('<?= $description_id ?>').value = `<?= __('Punto alle coordinate (EPSG:4326) Latitudine:') ?> ${coordinates[1]}, <?= __('Longitudine:') ?> ${coordinates[0]}`; |
|
|
|
empty_fields_from_geo_resources(geo_resources_mapped_fields); |
|
|
|
makeGetRequest(`/maps/geocode?address=${coordinates.join(",")}&geo_resources=${geo_resources}`) |
|
.then((contents) => { |
|
const selected_content = contents; |
|
if (document.getElementById('<?= $cap_id ?>')) document.getElementById('<?= $cap_id ?>').value = selected_content.cap; |
|
if (document.getElementById('<?= $province_id ?>')) document.getElementById('<?= $province_id ?>').value = selected_content.province; |
|
if (document.getElementById('<?= $district_code_id ?>')) document.getElementById('<?= $district_code_id ?>').value = selected_content.district_code; |
|
if (document.getElementById('<?= $district_id ?>')) document.getElementById('<?= $district_id ?>').value = selected_content.district; |
|
if (document.getElementById('<?= $address_id ?>')) document.getElementById('<?= $address_id ?>').value = selected_content.address; |
|
if (document.getElementById('<?= $description_id ?>')) document.getElementById('<?= $description_id ?>').value = selected_content.description; |
|
|
|
fill_fields_from_geo_resources(selected_content.geo_resources.mapped_fields); |
|
}) |
|
.catch((error) => alert("<?= __('Indirizzo non trovato o fuori dall\'area di competenza') ?>")); |
|
} |
|
|
|
function handle_result(index) { |
|
const selected_content = results[index]; |
|
const lonlat = [selected_content.lon, selected_content.lat]; |
|
const geocoded_point = new ol.Feature({ |
|
geometry: new ol.geom.Point(ol.proj.fromLonLat(lonlat)), |
|
}); |
|
drawInteractionVectorSource.addFeature(geocoded_point); |
|
updateDrawingLayerGeoJsons(); |
|
map.getView().animate({zoom: 10}, {center: ol.proj.transform(lonlat, 'EPSG:4326', 'EPSG:3857')}); |
|
geocodeWithCoordinates(lonlat); |
|
} |
|
|
|
let blinking_icon_handler = null; |
|
let blinking_status = false; |
|
|
|
function enable_blinking_geocoding_icon() { |
|
document.getElementById('jixel-address-button').setAttribute('disabled', true); |
|
document.getElementById('jixel-address-button').children.item(0).setAttribute('class', 'fa fa-hourglass'); |
|
blinking_icon_handler = setInterval(() => { |
|
if (blinking_status) { |
|
document.getElementById('jixel-address-button').children.item(0).setAttribute('class', 'fa fa-hourglass-o'); |
|
} else { |
|
document.getElementById('jixel-address-button').children.item(0).setAttribute('class', 'fa fa-hourglass'); |
|
} |
|
blinking_status = !blinking_status; |
|
}, 250); |
|
} |
|
|
|
function disable_blinking_geocoding_icon() { |
|
clearInterval(blinking_icon_handler); |
|
blinking_status = false; |
|
document.getElementById('jixel-address-button').children.item(0).setAttribute('class', 'fa fa-location-arrow'); |
|
document.getElementById('jixel-address-button').removeAttribute('disabled'); |
|
} |
|
|
|
function geocode(address) { |
|
disable_all_tools(); |
|
if (!address) return; |
|
enable_blinking_geocoding_icon(); |
|
|
|
makeGetRequest(`/maps/geocode?address=${address}`) |
|
.then((contents) => { |
|
disable_blinking_geocoding_icon(); |
|
Array.isArray(contents) || (contents = [contents]); |
|
results = contents; |
|
const result_items = contents.map((content, index) => `<li style="cursor: pointer;"><a onclick="handle_result(${index})" data-dismiss="modal">${content['display_name'] !== undefined ? content['display_name'] : content['lat'] + ',' + content['lon']}</a></li>`); |
|
document.getElementById('geocode-results-modal-body').innerHTML = `<ul>${result_items.join("")}</ul>`; |
|
$("#geocode-results-modal").modal().show(); |
|
}) |
|
.catch((error) => { |
|
disable_blinking_geocoding_icon(); |
|
alert("<?= __('Indirizzo non trovato o fuori dall\'area di competenza') ?>"); |
|
}); |
|
} |
|
<?php endif; ?> |
|
<?php if ($point || $polygon || $circle || $delete_geometry): ?> |
|
function disable_all_tools() { |
|
if (document.getElementById(`jixel-point-button`)) document.getElementById(`jixel-point-button`).style.color = ''; |
|
if (document.getElementById(`jixel-point-button`)) document.getElementById(`jixel-point-button`).style.backgroundColor = ''; |
|
if (document.getElementById(`jixel-polygon-button`)) document.getElementById(`jixel-polygon-button`).style.color = ''; |
|
if (document.getElementById(`jixel-polygon-button`)) document.getElementById(`jixel-polygon-button`).style.backgroundColor = ''; |
|
if (document.getElementById(`jixel-circle-button`)) document.getElementById(`jixel-circle-button`).style.color = ''; |
|
if (document.getElementById(`jixel-circle-button`)) document.getElementById(`jixel-circle-button`).style.backgroundColor = ''; |
|
if (document.getElementById(`jixel-delete-geometry-button`)) document.getElementById(`jixel-delete-geometry-button`).style.color = ''; |
|
if (document.getElementById(`jixel-delete-geometry-button`)) document.getElementById(`jixel-delete-geometry-button`).style.backgroundColor = ''; |
|
map.removeInteraction(drawPointInteraction); |
|
map.removeInteraction(drawPolygonInteraction); |
|
map.removeInteraction(drawCircleInteraction); |
|
map.removeInteraction(deleteGeometryInteraction); |
|
} |
|
|
|
function enable_tool(tool) { |
|
if (document.getElementById(`jixel-${tool}-button`)) document.getElementById(`jixel-${tool}-button`).style.color = 'white'; |
|
if (document.getElementById(`jixel-${tool}-button`)) document.getElementById(`jixel-${tool}-button`).style.backgroundColor = 'green'; |
|
switch (tool) { |
|
case 'point': |
|
map.addInteraction(drawPointInteraction); |
|
break; |
|
case 'polygon': |
|
map.addInteraction(drawPolygonInteraction); |
|
break; |
|
case 'circle': |
|
map.addInteraction(drawCircleInteraction); |
|
break; |
|
case 'delete-geometry': |
|
map.addInteraction(deleteGeometryInteraction); |
|
break; |
|
default: |
|
break; |
|
} |
|
} |
|
|
|
function toggle_tool(tool) { |
|
const tool_disabled = !document.getElementById(`jixel-${tool}-button`) || document.getElementById(`jixel-${tool}-button`).style.backgroundColor.length == 0; |
|
disable_all_tools(); |
|
if (tool_disabled) enable_tool(tool); |
|
} |
|
<?php endif; ?> |
|
<?php endif; ?> |
|
|
|
var map = new ol.Map({ |
|
controls: ol.control.defaults.defaults().extend(controls), |
|
layers: map_layers, |
|
overlays: [popupOverlay], |
|
target: 'olmap', |
|
view: new ol.View({ |
|
center: ol.proj.fromLonLat([<?= $config_center_lon ?>, <?= $config_center_lat ?>]), |
|
extent: ol.proj.transformExtent([<?= $upperLeftBoundLon ?>, <?= $upperLeftBoundLat ?>, <?= $lowerRightBoundLon ?>, <?= $lowerRightBoundLat ?>], 'EPSG:4326', 'EPSG:3857'), |
|
zoom: <?= $config_center_zoom ?>, |
|
minZoom: <?= $min_zoom_level ?>, |
|
}) |
|
}); |
|
|
|
map.addInteraction(selectInteraction); |
|
|
|
map.getLayerById = function (id) { |
|
let layer_found = false; |
|
this.getLayers().getArray().forEach((layer) => { |
|
layer_found || layer.get('id') == undefined || layer.get('id') !== id || (layer_found = layer); |
|
}); |
|
return layer_found; |
|
}; |
|
|
|
map.getLayerByCode = function (code) { |
|
let layer_found = false; |
|
this.getLayers().getArray().forEach((layer) => { |
|
layer_found || layer.get('code') == undefined || layer.get('code') !== code || (layer_found = layer); |
|
}); |
|
return layer_found; |
|
}; |
|
|
|
map.removeLayerById = function (id) { |
|
map.getLayers().getArray().filter(layer => layer.get('id') === id).forEach(layer => map.removeLayer(layer)); |
|
}; |
|
|
|
map.removeLayerByCode = function (code) { |
|
map.getLayers().getArray().filter(layer => layer.get('code') === code).forEach(layer => map.removeLayer(layer)); |
|
}; |
|
|
|
// per ogni attività sulla mappa, invochiamo checkOSM() |
|
// che si occupa di verificare, se siamo su OSM offline, lo stato di OSM online ed in caso switchare |
|
map.on("moveend", (evt) => { |
|
console.log(evt); |
|
typeof checkOSM === "undefined" || checkOSM(); |
|
}); |
|
|
|
<?php |
|
if (isset($get_current_position) && $get_current_position): |
|
?> |
|
// questo setTimeout serve solo a recuperare (se possibile) la posizione utente |
|
setTimeout(() => { |
|
navigator.geolocation.getCurrentPosition((pos) => { |
|
const coords = ol.proj.fromLonLat([pos.coords.longitude, pos.coords.latitude]); |
|
map.getView().animate({center: coords, zoom: 10}); |
|
}); |
|
}, 3000); |
|
<?php |
|
endif; |
|
?> |
|
|
|
// questa funzione gestisce l'eventuale zoom all'extent del layer passato come parametro |
|
function zoom_to_layer_with_id(id) |
|
{ |
|
const zoom_to_layer_wait_interval = setInterval(zoom_to_layer, 1000); |
|
let zoom_to_layer_wait_interval_attempts = 10; |
|
function zoom_to_layer() { |
|
if (zoom_to_layer_wait_interval_attempts) { |
|
zoom_to_layer_wait_interval_attempts--; |
|
console.log("zoom_to_layer called!"); |
|
if (typeof map == "undefined") { console.log("zoom_to_layer: map is NOT ready!"); return; } |
|
if (typeof map.getLayerById == "undefined") { console.log("zoom_to_layer: map.getLayerById() method is NOT ready!"); return; } |
|
layer_to_zoom_into = map.getLayerById(id); |
|
if (!layer_to_zoom_into) { console.log("zoom_to_layer: layer not found!"); return; } |
|
if (layer_to_zoom_into.getSource().getFeatures().length == 0) { console.log("zoom_to_layer: no features detected!"); return; } |
|
let layerExtent = layer_to_zoom_into.getSource().getExtent(); |
|
if (layerExtent.filter(item => !isNaN(item) && isFinite(item)).length != 4) { console.log("zoom_to_layer: invalid layerExtent received!"); return; } |
|
if (layerExtent[0] == layerExtent[2] && layerExtent[1] == layerExtent[3]) { |
|
console.log("zoom_to_layer: layerExtent is just a point wise. trying to get cluster features extent..."); |
|
const new_source = new ol.source.Vector(); |
|
new_source.addFeatures(layer_to_zoom_into.getSource().getFeatures()[0].get('features')); |
|
layerExtent = new_source.getExtent(); |
|
} |
|
geom = ol.geom.Polygon.fromExtent(layerExtent); |
|
geom.scale(1.2); |
|
map.getView().fit(geom, {duration: 2000}); |
|
console.log("zoom_to_layer: job done!"); |
|
} |
|
clearInterval(zoom_to_layer_wait_interval); |
|
console.log("zoom_to_layer: removing handler!"); |
|
} |
|
} |
|
const zoom_to_layer_id = map.getLayers().getArray().filter(layer => layer.get('zoom_to_layer')).map(layer => layer.get('id')).reduce((acc, id) => { return id; }, null); |
|
if (zoom_to_layer_id) zoom_to_layer_with_id(zoom_to_layer_id); |
|
|
|
// questo observer serve a fixare le proporzioni della mappa a seguito di collapse in o out del menu di sx |
|
const body_observer = new MutationObserver((mr) => { |
|
console.log("OLMap body_observer MUTATION RECORD:"); |
|
console.log(mr); |
|
if (mr.length > 0 && mr[0].type === 'attributes' && mr[0].attributeName === 'class') { |
|
console.log("OLMap TRIGGER MAP UPDATE SIZE HERE!"); |
|
setTimeout(() => { |
|
console.log("OLMap updateSize TRIGGERED!"); |
|
map.updateSize(); |
|
}, 500); |
|
} |
|
}).observe(document.body, {attributes: true}); |
|
|
|
<?php if ($tools): ?> |
|
// creazione oggetto di interazione mappa di tipo Draw |
|
var drawingLayerGeoJson_3857 = ''; |
|
var drawingLayerGeoJson_4326 = ''; |
|
const drawInteractionVectorSource = new ol.source.Vector({wrapX: false}); |
|
|
|
const drawInteractionVectorLayer = new ol.layer.Vector({ |
|
name: '<?= $drawing_layer_name ?>', |
|
source: drawInteractionVectorSource, |
|
style: selectedStyleFunctionGenerator(), |
|
}); |
|
|
|
map.getLayers().push(drawInteractionVectorLayer); |
|
|
|
var drawPointInteraction = new ol.interaction.Draw({ |
|
source: drawInteractionVectorSource, |
|
type: 'Point', |
|
}); |
|
|
|
var drawPolygonInteraction = new ol.interaction.Draw({ |
|
source: drawInteractionVectorSource, |
|
type: 'Polygon', |
|
}); |
|
|
|
var drawCircleInteraction = new ol.interaction.Draw({ |
|
source: drawInteractionVectorSource, |
|
type: 'Circle', |
|
geometryFunction: ol.interaction.Draw.createRegularPolygon(), |
|
}); |
|
|
|
function updateDrawingLayerGeoJsons() { |
|
// questo timeout serve per eseguire il codice al di fuori dell'handler che lo invoca |
|
setTimeout(() => { |
|
<?php if (!$multiple_points): ?> |
|
const point_features = drawInteractionVectorSource.getFeatures().filter(feature => feature.getGeometry().getType() == 'Point'); |
|
if (point_features.length > 1) { |
|
drawInteractionVectorSource.removeFeature(point_features[0]); |
|
} |
|
const lonlat = point_features.length > 0 ? point_features[point_features.length - 1].clone().getGeometry().transform('EPSG:3857', 'EPSG:4326').getCoordinates() : ['', '']; |
|
const location = {longitude: lonlat[0], latitude: lonlat[1]}; |
|
if (document.getElementById('<?= $longitude_id ?>')) document.getElementById('<?= $longitude_id ?>').value = location.longitude; |
|
if (document.getElementById('<?= $latitude_id ?>')) document.getElementById('<?= $latitude_id ?>').value = location.latitude; |
|
if (document.getElementById('<?= $coordinates_id ?>')) document.getElementById('<?= $coordinates_id ?>').value = `${location.longitude} ${location.latitude}`; |
|
<?php endif; ?> |
|
drawingLayerGeoJson_3857 = new ol.format.GeoJSON().writeFeatures(drawInteractionVectorSource.getFeatures()); |
|
cloned_features = []; |
|
drawInteractionVectorSource.getFeatures().forEach(feature => cloned_features.push(feature.clone())); |
|
cloned_features.forEach(feature => feature.getGeometry().transform('EPSG:3857', 'EPSG:4326')); |
|
drawingLayerGeoJson_4326 = new ol.format.GeoJSON().writeFeatures(cloned_features); |
|
if (document.getElementById('<?= $feature_collection_id ?>')) document.getElementById('<?= $feature_collection_id ?>').value = drawingLayerGeoJson_4326; |
|
}, 0); |
|
} |
|
|
|
drawPointInteraction.on('drawend', function(evt) { |
|
console.log('drawPointInteraction drawend!'); |
|
console.log(evt); |
|
<?php if (!$multiple_points): ?> |
|
const coordinates = evt.feature.clone().getGeometry().transform('EPSG:3857', 'EPSG:4326').flatCoordinates; |
|
typeof geocodeWithCoordinates === "function" && geocodeWithCoordinates(coordinates); |
|
<?php endif; ?> |
|
updateDrawingLayerGeoJsons(); |
|
}); |
|
|
|
drawPolygonInteraction.on('drawend', function(evt) { |
|
console.log('drawPolygonInteraction drawend!'); |
|
console.log(evt); |
|
updateDrawingLayerGeoJsons(); |
|
}); |
|
|
|
drawCircleInteraction.on('drawend', function(evt) { |
|
console.log('drawCircleInteraction drawend!'); |
|
console.log(evt); |
|
updateDrawingLayerGeoJsons(); |
|
}); |
|
|
|
// creazione oggetto di interazione mappa di tipo select per cancellare le features selezionate |
|
var deleteGeometryInteraction = new ol.interaction.Select({ |
|
layers: [drawInteractionVectorLayer], |
|
}); |
|
|
|
// gestione delete selected feature |
|
deleteGeometryInteraction.on('select', function(evt) { |
|
<?php if (!$multiple_points): ?> |
|
const point_features = this.getFeatures().getArray().filter(feature => feature.getGeometry().getType() == 'Point'); |
|
if (point_features.length > 0) { |
|
if (document.getElementById('<?= $cap_id ?>')) document.getElementById('<?= $cap_id ?>').value = ''; |
|
if (document.getElementById('<?= $province_id ?>')) document.getElementById('<?= $province_id ?>').value = ''; |
|
if (document.getElementById('<?= $district_code_id ?>')) document.getElementById('<?= $district_code_id ?>').value = ''; |
|
if (document.getElementById('<?= $district_id ?>')) document.getElementById('<?= $district_id ?>').value = ''; |
|
if (document.getElementById('<?= $address_id ?>')) document.getElementById('<?= $address_id ?>').value = ''; |
|
if (document.getElementById('<?= $description_id ?>')) document.getElementById('<?= $description_id ?>').value = ''; |
|
typeof empty_fields_from_geo_resources === "function" && empty_fields_from_geo_resources(geo_resources_mapped_fields); |
|
} |
|
<?php endif; ?> |
|
this.getFeatures().getArray().forEach(feature => drawInteractionVectorSource.removeFeature(feature)); |
|
this.getFeatures().clear(); |
|
map.render(); |
|
updateDrawingLayerGeoJsons(); |
|
}); |
|
|
|
window.addEventListener('DOMContentLoaded', function() { |
|
if (document.getElementById('<?= $feature_collection_id ?>') && document.getElementById('<?= $feature_collection_id ?>').value.length > 0) { |
|
try { |
|
JSON.parse(document.getElementById('<?= $feature_collection_id ?>').value); |
|
const initial_features = new ol.format.GeoJSON().readFeatures(document.getElementById('<?= $feature_collection_id ?>').value, {dataProjection: 'EPSG:4326'}); |
|
initial_features.forEach(initial_feature => initial_feature.getGeometry().transform('EPSG:4326', 'EPSG:3857')); |
|
drawInteractionVectorSource.addFeatures(initial_features); |
|
updateDrawingLayerGeoJsons(); |
|
} catch (error) { |
|
console.log('feature_collection field value is invalid!'); |
|
} |
|
} |
|
}); |
|
<?php endif; ?> |
|
</script>
|
|
|