// ======================================================
// ======================================================
//
// senderismetk.js v1.0, April 2021
// Justino Martinez
// Senderisme i Teca, 2021
//
// Adapted from the old googleRaster30 based on Google Maps
//
// ======================================================
// ======================================================
const MiURL="https://senderisme.tk";
const MiICO="/wp-content/icons_googlemaps/";
const MiFOT="/wp-content/fotos_googlemaps/";
var _zoom0=7.5;
const _zoommin=2;
const _zoommax=21;
const _totalControls=9;
var zxs="/wp-content/kml_googlemaps/999999_g.kml";
var iskml=true;
const _XMLlist="/wp-random.php";
const _XMLlistWiki="/wp-wiki.php";
const _centerL =[1.75,41.75];
const _projection='EPSG:3857';
var _center=ol.proj.transform(_centerL,'EPSG:4326',_projection);
var _coordMouse;
// Shows info about the route
var track=null;
var sourceTrack=null;
var kmlformat=null;
var gpxformat=null;
proj4.defs("EPSG:25831","+proj=utm +zone=31 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs");
ol.proj.proj4.register(proj4);
//-------------------------
// Supp functions
//-------------------------
function showResolution(){
// Resoluccio mapa
var currentZoom = map.getView().getZoom();
var resolution="1:5000";
if (currentZoom < 16.5){
resolution="1:25000";
}
if (currentZoom < 14.3){
resolution="1:50000";
}
if (currentZoom < 12.4){
resolution="1:100000";
}
if (currentZoom < 11.3){
resolution="1:250000";
}
if (currentZoom < 10.4){
resolution="1:500000";
}
if (currentZoom < 9.4){
resolution="1:1000000";
}
if (currentZoom < 8.3){
resolution="1:2000000";
}
$("#resolution").html("Resolució ICC: "+resolution);
}
function hideResolution(){
$("#resolution").html("Resolució: --");
}
function checkMouseInfo(e) {
let text="";
let absC=[0,0];
let i,j;
let LA="N";
let LO="E"
var coordMouse;
_coordMouse=e.coordinate;
coordMouse=ol.proj.transform(_coordMouse,_projection,'EPSG:4326');
if (coordMouse[0]<0) LO="W";
if (coordMouse[1]<0) LA="S";
absC[0]=Math.abs(coordMouse[0]);
absC[1]=Math.abs(coordMouse[1]);
text=absC[0].toFixed(3)+"°"+LO+" / "+absC[1].toFixed(3)+"°"+LA
document.getElementById("mouseInfo").innerHTML =text;
}
//------------------------------
// Background Map and Layers
//------------------------------
var inspireWgs84Grid = function(levels, prefix) {
var projection = ol.proj.get('EPSG:4326');
var projectionExtent = projection.getExtent();
var resolution = ol.extent.getWidth(projectionExtent) / 512;
var resolutions = new Array(levels);
var matrixIds = new Array(levels);
for (var z = 0; z < levels; z++) {
resolutions[z] = resolution / Math.pow(2, z);
matrixIds[z] = z;
}
return new ol.tilegrid.WMTS({
origin: ol.extent.getTopLeft(projectionExtent),
resolutions: resolutions,
matrixIds: matrixIds
});
}
const att_emodnet = "
© EMODnet Bathymetry Consortium (2018): EMODnet Digital Bathymetry (DTM)."
const emodnet = new ol.layer.Tile({
opacity: 0.5,
visible: false,
title: "EMODNET: Relleu",
source : new ol.source.WMTS({
url : 'https://tiles.emodnet-bathymetry.eu/2020/baselayer/{TileMatrixSet}/{TileMatrix}/{TileCol}/{TileRow}.png',
layer : 'baselayer',
wrapX:!0,
crossOrigin: 'anonymous',
requestEncoding : 'REST',
matrixSet : 'inspire_quad',
format : 'image/png',
projection : "EPSG:4326",
tileGrid : inspireWgs84Grid(12, ''),
attributions: att_emodnet,
cacheSize: 512,
})
});
//emodnet.getSource().tileCache.setSize(512);
_opacityLand0=0.6;
const emodnetLand = new ol.layer.Tile({
opacity: _opacityLand0,
visible: false,
title: "EMODNET: Relleu",
source : new ol.source.WMTS({
url : 'https://tiles.emodnet-bathymetry.eu/2020/baselayer_land/{TileMatrixSet}/{TileMatrix}/{TileCol}/{TileRow}.png',
layer : 'baselayer_land',
wrapX:!0,
crossOrigin: 'anonymous',
requestEncoding : 'REST',
matrixSet : 'inspire_quad',
format : 'image/png',
projection : "EPSG:4326",
attributions: att_emodnet,
tileGrid : inspireWgs84Grid(12, '')
})
});
var base = new ol.layer.Tile({
title: "Mapa Base",
//type: 'base',
source: new ol.source.OSM({}),
opacity:1,
visible:true,
crossOrigin: 'anonymous',
cacheSize: 512,
});
var attICCtopo="
© Institut Cartogràfic de Catalunya. Mapa topogràfic.";
var attICCorto="
© Institut Cartogràfic de Catalunya. Fotografia ortogràfica.";
var ICCorto = new ol.layer.Tile({
title: "Ortofoto ICC",
//type: 'base',
source: new ol.source.TileWMS({
//url: 'https://tilemaps.icgc.cat/mapfactory/service',
url: 'https://geoserveis.icgc.cat/icc_mapesmultibase/utm/wms/service?',
//params: {'LAYERS':'osm_suau','SRS':'EPSG:4326'},
params: {'LAYERS':'orto'},
wrapX:!0,
crossOrigin: 'anonymous',
cacheSize: 512,
attributions: attICCorto,
}),
opacity: 1,
visible:false,
})
var ICCtopo = new ol.layer.Tile({
title: "Topogràfic ICC",
extent: ol.proj.transformExtent([0.144,40.518,3.404,42.876],'EPSG:4326',_projection),
source: new ol.source.TileWMS({
//url: 'https://tilemaps.icgc.cat/mapfactory/service',
//params: {'LAYERS':'osm_suau','SRS':'EPSG:4326'},
url: 'https://geoserveis.icgc.cat/icc_mapesmultibase/utm/wms/service?',
params: {'LAYERS':'topo'},
wrapX:!0,
crossOrigin: 'anonymous',
cacheSize: 512,
attributions: attICCtopo,
}),
maxZoom: 20,
opacity: 1,
visible:false,
})
var attICEtopo="
© Instituto Geográfico Nacional. http://www.scne.es/";
var ICEtopo = new ol.layer.Tile({
title: "Topogràfic IGN",
source: new ol.source.TileWMS({
//url: 'https://tilemaps.icgc.cat/mapfactory/service',
//params: {'LAYERS':'osm_suau','SRS':'EPSG:4326'},
url: 'http://www.ign.es/wms-inspire/mapa-raster?SERVICE=WMS&',
params: {'LAYERS':'mtn_rasterizado'},
wrapX:!0,
crossOrigin: 'anonymous',
cacheSize: 512,
attributions: attICEtopo,
}),
maxZoom: 20,
opacity: 1,
visible:false,
})
var projection = ol.proj.get('EPSG:3857');
var projectionExtent = projection.getExtent();
var size = ol.extent.getWidth(projectionExtent) / 256;
var resolutions = new Array(21);
var matrixIds = new Array(21);
for (var z = 0; z < 21; ++z) {
// generate resolutions and matrixIds arrays for this WMTS
resolutions[z] = size / Math.pow(2, z);
matrixIds[z] = z;
}
var ICEorto = new ol.layer.Tile({
title: "Ortofoto IGN",
source: new ol.source.WMTS({
url: 'https://www.ign.es/wmts/pnoa-ma?',
layer: 'OI.OrthoimageCoverage',
matrixSet: 'EPSG:3857',
format: 'image/png',
projection: projection,
tileGrid: new ol.tilegrid.WMTS({
origin: ol.extent.getTopLeft(projectionExtent),
resolutions: resolutions,
matrixIds: matrixIds,
}),
style: 'default',
wrapX:!0,
crossOrigin: 'anonymous',
cacheSize: 512,
attributions: attICEtopo,
}),
maxZoom: 22,
opacity: 1,
visible:false,
})
// Only one ICC layer at the same time
ICCtopo.on("change", function(e) {
if (ICCtopo.getVisible()== false){
hideResolution();
} else {
if (ICCorto.getVisible()== true){
ICCorto.setVisible(false);
}
if (ICEtopo.getVisible()== true){
ICEtopo.setVisible(false);
}
if (ICEorto.getVisible()== true){
ICEorto.setVisible(false);
}
}
});
ICCorto.on("change", function(e) {
if (ICCorto.getVisible()== false){
hideResolution();
} else {
if (ICCtopo.getVisible()== true){
ICCtopo.setVisible(false);
}
if (ICEtopo.getVisible()== true){
ICEtopo.setVisible(false);
}
if (ICEorto.getVisible()== true){
ICEorto.setVisible(false);
}
}
});
ICEtopo.on("change", function(e) {
if (ICEtopo.getVisible()== false){
hideResolution();
} else {
if (ICCorto.getVisible()== true){
ICCorto.setVisible(false);
}
if (ICCtopo.getVisible()== true){
ICCtopo.setVisible(false);
}
if (ICEorto.getVisible()== true){
ICEorto.setVisible(false);
}
}
});
ICEorto.on("change", function(e) {
if (ICEorto.getVisible()== false){
hideResolution();
} else {
if (ICCorto.getVisible()== true){
ICCorto.setVisible(false);
}
if (ICCtopo.getVisible()== true){
ICCtopo.setVisible(false);
}
if (ICEtopo.getVisible()== true){
ICEtopo.setVisible(false);
}
}
});
// Overlay to store popups
var containerPopup = document.getElementById('popup');
var contentPopup = document.getElementById('popup-content');
var closerPopup = document.getElementById('popup-closer');
var overlayPopup = new ol.Overlay({
element: containerPopup,
autoPan: true,
autoPanAnimation: {
duration: 250,
},
});
// ======================================================
// General styles
// ======================================================
const styles = {
'Point': new ol.style.Style({
image: new ol.style.Circle({
fill: new ol.style.Fill({ color: 'rgba(255,255,0,1)' }),
radius:7, stroke: new ol.style.Stroke({color:'red',width:3})
}),
text: new ol.style.Text({
font: '18px Calibri,sans-serif',
overflow: true,
offsetX: 50,
offsetY: 25,
fill: new ol.style.Fill({color: '#000'}),
stroke: new ol.style.Stroke({color: '#fff',width: 3}),
}),
}),
'LineString': new ol.style.Style({
stroke: new ol.style.Stroke({color:'#f00',width:3})
}),
'Polygon': new ol.style.Style({
stroke: new ol.style.Stroke({color:'#f00',width:3})
}),
'MultiLineString': new ol.style.Style({
stroke: new ol.style.Stroke({color:'#0f0',width:3})
}),
'geoMarker': new ol.style.Style({
text: new ol.style.Text({
font: '18px Calibri,sans-serif',
overflow: true,
offsetX: 50,
offsetY: 25,
fill: new ol.style.Fill({color: '#000'}),
stroke: new ol.style.Stroke({color: '#fff',width: 3}),
}),
stroke: new ol.style.Stroke({color:'red',width:5}),
image: new ol.style.Circle({
opacity:1,
radius:8,
snapToPixel: false,
fill: new ol.style.Fill({color: 'black'}),
stroke: new ol.style.Stroke({color:'red',width:2})
})
}),
};
// ======================================================
// Drag and drop
// ======================================================
var dragAndDropInteraction;
let _DDlayers = []; // array of DD layers
var _DDvectorSource;
function setDDInteraction() {
var name="";
var styleFunction = function(feature, resolution) {
var namef,stylef,typef;
var featureStyleFunction = feature.getStyleFunction();
if (featureStyleFunction)
return featureStyleFunction.call(feature, resolution);
else
namef=feature.get('name');
typef=feature.getGeometry().getType();
stylef=styles[feature.getGeometry().getType()];
if (typef=='Point') stylef.getText().setText(namef);
if (typef=='MultiLineString') {
name=feature.get('name');
}
return stylef;
};
let texte;
if (dragAndDropInteraction) {
map.removeInteraction(dragAndDropInteraction);
}
dragAndDropInteraction = new ol.interaction.DragAndDrop({
formatConstructors: [
ol.format.GPX,
ol.format.GeoJSON,
ol.format.IGC,
ol.format.TopoJSON,
ol.format.KML]
});
dragAndDropInteraction.on('addfeatures', function (event) {
name = event.file.name.split('.')[0];
if (event.features.length > 1){
rCoords = event.features[1].getGeometry().getCoordinates();
// Modify feature accordingly
if (rCoords.length<1){
texte=name+" no conté dades";
$("#alertid").html(texte);
$("#alert").dialog({ modal: true,
buttons: {
"Ok": function() { // we drop the
$(this).dialog( "close");
},
}
});
return
}
}
_DDvectorSource = new ol.source.Vector({
features: event.features,
});
let nlay=_DDlayers.length;
_DDlayers[nlay]=new ol.layer.Vector({
title:name,
source: _DDvectorSource,
style: styleFunction,
crossOrigin: 'anonymous',
visible: true,
});
_DDlayers[nlay].set('name',_DDlayers.length);
groupLayersUSER.getLayers().getArray().push(_DDlayers[nlay]);
map.addLayer(groupLayersUSER);
_DDlayers[nlay].setVisible(true);
map.getView().fit(_DDvectorSource.getExtent());
});
map.addInteraction(dragAndDropInteraction);
}
function eliminaTracks(){
for (i=0;i<_DDlayers.length;i++){
groupLayersUSER.getLayers().getArray().pop();
}
_DDlayers=[];
map.removeLayer(groupLayersUSER);
}
// ======================================================
// Loads the map and related functions
// ======================================================
var map;
var attribution = new ol.control.Attribution({
collapsible: true,
});
// format for graticule text
var latFormatter= function(lat) {
var formattedLat = Math.abs(Math.round(lat * 100) / 100);
formattedLat += (lat < 0) ? 'S' : ((lat > 0) ? 'N' : '');
return formattedLat;
};
var lonFormatter = function(lon) {
var formattedLon = Math.abs(Math.round(lon * 100) / 100);
formattedLon += (lon < 0) ? 'W' : ((lon > 0) ? 'E' : '');
return formattedLon;
};
var scaleType="scalebar"
var _scaleControl;
var scaleBar = function(scaleType) {
control=null;
if (scaleType === 'scaleline') {
control = new ol.control.ScaleLine({
units: 'metric', //degrees, imperial,us, metric,nautical
});
}
if (scaleType == 'scalebar'){
control = new ol.control.ScaleLine({
units: 'metric',
bar: true,
steps: 4,
text: false,
minWidth: 150,
});
}
return control;
}
var mapView=new ol.View({
center: _center,
//extent: ol.proj.transformExtent(_extent,'EPSG:4326',_projection),
zoom: _zoom0,
minZoom: _zoommin,
maxZoom: _zoommax,
})
var groupLayersUSER=new ol.layer.Group({
'title': 'Tracks',
layers:[],
})
function loadMap() {
var graticuleLine = new ol.layer.Graticule({
title: "Retícula",
// the style to use for the lines, optional.
strokeStyle: new ol.style.Stroke({
color: 'rgba(220,220,220,1)',
width: 2,
lineDash: [0.5, 4]
}),
showLabels: false,
wrapX: true,
targetSize: 100,
visible: false
});
var graticule = new ol.layer.Graticule({
title: "Eixos principals",
// the style to use for the lines, optional.
strokeStyle: new ol.style.Stroke({
color: 'rgba(220,220,220,0)',
width: 2,
lineDash: [0.5, 4]
}),
showLabels: true,
wrapX: true,
targetSize: 100,
latLabelStyle: new ol.style.Text({
font: '14px Arial, Helvetica, sans-serif',
textAlign: 'begin',
fill: new ol.style.Fill({
color: 'rgba(0,0,0,1)',
}),
stroke: new ol.style.Stroke({
color: 'rgba(255,255,255,0.8)',
width: 3
})
}),
lonLabelStyle: new ol.style.Text({
font: '14px Arial, Helvetica, sans-serif',
textBaseline: 'bottom',
fill: new ol.style.Fill({
color: 'rgba(0,0,0,1)',
}),
stroke: new ol.style.Stroke({
color: 'rgba(255,255,255,0.8)',
width: 3
})
}),
latLabelFormatter: latFormatter,
lonLabelFormatter: lonFormatter,
latLabelPosition: 0.01
});
var graticuleSecondary = new ol.layer.Graticule({
title: "Eixos secundaris",
// the style to use for the lines, optional.
strokeStyle: new ol.style.Stroke({
color: 'rgba(220,220,220,0)',
width: 2,
lineDash: [0.5, 4]
}),
showLabels: true,
wrapX: true,
targetSize: 100,
latLabelStyle: new ol.style.Text({
font: '14px Arial, Helvetica, sans-serif',
textAlign: 'end',
fill: new ol.style.Fill({
color: 'rgba(0,0,0,1)',
}),
stroke: new ol.style.Stroke({
color: 'rgba(255,255,255,0.8)',
width: 3
})
}),
lonLabelStyle: new ol.style.Text({
font: '14px Arial, Helvetica, sans-serif',
textBaseline: 'top',
fill: new ol.style.Fill({
color: 'rgba(0,0,0,1)',
}),
stroke: new ol.style.Stroke({
color: 'rgba(255,255,255,0.8)',
width: 3
})
}),
latLabelFormatter: latFormatter,
lonLabelFormatter: lonFormatter,
latLabelPosition: 0.99,
lonLabelPosition: 0.99
});
// Layers groups
var groupLayersLabels=new ol.layer.Group({
'title': 'Etiquetes',
layers:[graticuleLine,graticule,graticuleSecondary]
})
var groupLayers=new ol.layer.Group({
'title': 'EMODnet',
layers:[emodnetLand]
})
var groupLayersICC=new ol.layer.Group({
'title': 'Cartogràfics',
layers:[ICCorto,ICCtopo,ICEorto,ICEtopo],
visible: true,
})
map = new ol.Map({
layers: [base,groupLayersICC,groupLayers,groupLayersLabels],
target: 'map',
controls: new ol.control.defaults({attribution: false}).extend([attribution]), //.defaults().extend([mousePositionControl]),
overlays:[overlayPopup],
view: mapView,
});
attribution.setCollapsed(true);
_scaleControl=scaleBar(scaleType);
map.addControl(_scaleControl);
// Button that centers map to its original position and zoom
var buttonCenter = document.createElement('button');
buttonCenter.innerHTML = '⛶';
buttonCenter.setAttribute("title", "Tornar a la posició inicial");
buttonCenter.addEventListener('click', centerMap, false);
var elementCenter = document.createElement('div');
elementCenter.className = 'rotate-north ol-unselectable ol-control';
elementCenter.appendChild(buttonCenter);
var centerControl = new ol.control.Control({
element:elementCenter,
});
map.addControl(centerControl);
// Button that takes screen-shot
var buttonShot = document.createElement('button');
buttonShot.innerHTML = '☈';
buttonShot.setAttribute("id", "snapshot");
buttonShot.setAttribute("title", "Capturar mapa");
buttonShot.addEventListener('click', snapShot, false);
var elementShot = document.createElement('div');
elementShot.className = 'rotate-north shot-element ol-unselectable ol-control';
elementShot.appendChild(buttonShot);
var shotControl = new ol.control.Control({
element:elementShot,
});
map.addControl(shotControl);
// Button that shows info about a track
var buttonTrack = document.createElement('button');
buttonTrack.innerHTML = '?';
buttonTrack.setAttribute("id", "track");
buttonTrack.setAttribute("title", "Mostra/amaga informació sobre el track");
buttonTrack.addEventListener('click', showTrackInfo, false);
var elementTrack = document.createElement('div');
elementTrack.className = 'rotate-north track-element ol-unselectable ol-control';
elementTrack.appendChild(buttonTrack);
var trackControl = new ol.control.Control({
element:elementTrack,
});
map.addControl(trackControl);
// Button that shows scale
var buttonScale = document.createElement('button');
buttonScale.innerHTML = 'E';
buttonScale.setAttribute("id", "scale");
buttonScale.setAttribute("title", "Mostra/amaga l'escala");
buttonScale.addEventListener('click', putScale, false);
var elementScale = document.createElement('div');
elementScale.className = 'rotate-north scale-element ol-unselectable ol-control';
elementScale.appendChild(buttonScale);
var scaleControl = new ol.control.Control({
element:elementScale,
});
map.addControl(scaleControl);
// Layer Switcher
layersw = new ol.control.LayerSwitcher();
map.addControl(layersw);
graticuleLine.setZIndex(3100);
graticule.setZIndex(3101);
graticuleSecondary.setZIndex(3102);
map.on("moveend", function(e) {
if ((ICCtopo.getVisible()== true)||(ICCorto.getVisible()== true)){
showResolution();
} else {
hideResolution();
}
if ((zxs=="")&&(map.getView().getZoom()<11)) {
deleteTrack();
}
});
ICCtopo.on('change:visible', function() {
if (this.getVisible()== true){
ICCorto.setVisible(false);
ICEtopo.setVisible(false);
ICEorto.setVisible(false);
showResolution();
} else {
hideResolution();
}
});
ICCorto.on('change:visible', function() {
if (this.getVisible()== true){
ICCtopo.setVisible(false);
ICEtopo.setVisible(false);
ICEorto.setVisible(false);
showResolution();
} else {
hideResolution();
}
});
ICEtopo.on('change:visible', function() {
if (this.getVisible()== true){
ICCorto.setVisible(false);
ICCtopo.setVisible(false);
ICEorto.setVisible(false);
}
hideResolution();
});
ICEorto.on('change:visible', function() {
if (this.getVisible()== true){
ICCorto.setVisible(false);
ICCtopo.setVisible(false);
ICEtopo.setVisible(false);
}
hideResolution();
});
emodnetLand.on('change:visible', function() {
if ( this.getVisible()== true){
$("#opacity-bar").show();
$("#opacity-text").show();
} else {
$("#opacity-bar").hide();
$("#opacity-text").hide();
}
});
map.addOverlay(overlayTooltip);
map.addEventListener('pointermove',checkMouseInfo);
if (zxs == "/wp-content/kml_googlemaps/999999_g.kml") setDDInteraction();
}
// -------------------------------------------------------------------
// Simply open/close the message box
// -------------------------------------------------------------------
function messageBox(message){
$("#loading").dialog("open").html(""+message+"
");
}
function closeBox(){
$("#loading").dialog("close");
}
// -------------------------------------------------------------------
// Opacity control
// -------------------------------------------------------------------
$("#opacity-bar").slider({
value:_opacityLand0*100,
min:0.0,
max:100,
change: function(event,ui){
let nx=$("#opacity-bar").slider("value");
emodnetLand.setOpacity(nx/100);
}
});
$("#tooltip").hide();
/////////////////////////////////////////////////////
// Main options
/////////////////////////////////////////////////////
// -------------------------------------------------------------------
// Loading dialog
// -------------------------------------------------------------------
$("#loading").dialog({
autoOpen: false,
height: 250,
width: 500,
modal: true,
draggable: false,
resizable: false,
closeOnEscape: false,
title: 'Un moment, si us plau',
open: function(event, ui) {
$(".ui-dialog-titlebar-close", ui.dialog || ui).hide();
},
close: function () {
}
});
// -------------------------------------------------------------------
// Scale barr
// -------------------------------------------------------------------
var putScale = function() {
if (map.getControls().get("length") == _totalControls){
map.removeControl(_scaleControl);
} else {
map.addControl(_scaleControl);
}
}
// -------------------------------------------------------------------
// Screen-shot
// -------------------------------------------------------------------
var snapShot = function() {
var exportpng= document.querySelector('#snapshot');
map.once('rendercomplete', function(event) {
domtoimage.toPng(map.getViewport().querySelector('.ol-layers')).then(function(dataUrl) {
var tmpa = document.createElement('a');
tmpa.href =dataUrl;
tmpa.download = 'senderisme_i_teca.png';
tmpa.style = 'display: none';
exportpng.parentNode.appendChild(tmpa);
tmpa.click();
tmpa.remove();
});
});
map.renderSync();
};
// -------------------------------------------------------------------
// Center map to its original position and zoom
// -------------------------------------------------------------------
function centerMap(){
map.getView().setCenter(_center);
map.getView().setZoom(_zoom0);
}
// Load location and routes data
var sourceRoutes = [];
var Routes = []
var Rfeatures=[];
var startingPointStyle=[];
var banderetaNou=[];
for (i=0;i<4;i++){
banderetaNou[i]=MiICO+"bandereta_"+(i+1)+".png";
startingPointStyle[i]=new ol.style.Style({
image: new ol.style.Icon({
anchor: [13, 32],
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
src: banderetaNou[i]
}),
});
}
startingPointStyle[4]=new ol.style.Style({
image: new ol.style.Icon({
anchor: [13, 32],
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
src: MiICO+"bandereta.png"
}),
});
var startingPointStyleWiki=new ol.style.Style({
image: new ol.style.Icon({
anchor: [13, 32],
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
src: MiICO+"bandereta_v.png"
}),
});
let xmlFormat = new ol.format.OSMXML({});
var selected = null;
var closePop = function (){
isshowntrackinfo=false;
overlayPopup.setPosition(undefined);
closerPopup.blur();
}
closerPopup.onclick = function () {
closePop();
return false;
};
// Auto popup showin the name of the route
function checkRouteInfo(eve){
var feature= map.forEachFeatureAtPixel(eve.pixel, function (f) {
return f;
});
tooltip.style.display = feature ? '' : 'none';
if (feature) {
if (typeof feature.get('title') !== 'undefined') {
overlayTooltip.setPosition(eve.coordinate);
tooltip.innerHTML = feature.get('title');
} else {
tooltip.style.display = 'none';
}
}
}
function deleteTrack(){
if (track != null){
groupLayersUSER.getLayers().getArray().pop();
map.removeLayer(groupLayersUSER);
//track.setMap(null);
track=null;
trackHTML=textTrack("Track no seleccionat","No hi ha informació disponible.");
}
}
function showRouteInfo(eve){
var selectedtmp=null;
selectedtmp = map.forEachFeatureAtPixel(eve.pixel, function (f) {
return f;
});
if (selectedtmp == null) {
return false;
}
if (track != null){
if (typeof selectedtmp.get('name') !== 'undefined'){
if (selectedtmp.get('name') == "Consulteu la ruta"){
if (typeof selected.get('link') !== 'undefined') {
if (selected.get('win')=="_blank"){
window.open(selected.get('link'));
} else {
messageBox('Carregant la descripció');
window.location.href=selected.get('link');
}
return true;
}
}
}
}
if (selectedtmp.get('startPoint') != true) {
return false;
}
selected=selectedtmp.clone();
deleteTrack();
var randomNum=Math.random();
var titol=selected.get('title');
var titfunc=titol.replace(/'/g, "\\'");
var link=selected.get('link');
var imgsrc=selected.get('img');
var descripcio=selected.get('description');
var link_track=selected.get('link_track');
var idtrack=selected.get('name');
var kml=true;
if (idtrack*1>=10000){
kml=false;
}
//Posem les darreres rutes a la vista
html = '';
if (kml){
html += '

';
}
html += '
'+titol+''
+ '
'+ descripcio + ''
+ '
';
if ( link_track != ""){
html += '

';
}
if (!kml){
html += '

';
} else {
html += '

';
}
html+= '';
contentPopup.innerHTML=html;
//$(".ol-popup-closer").show();
overlayPopup.setPosition(_coordMouse);
}
var isshowntrackinfo=false;
function showTrackInfo(){
var extent,lo;
if (isshowntrackinfo==true){
closePop();
} else {
contentPopup.innerHTML=trackHTML;
extent=map.getView().calculateExtent()
lo=extent[0]+(extent[2]-extent[0])/5
overlayPopup.setPosition([lo, extent[1]]);
isshowntrackinfo=true;
}
}
function textTrack(titol,desc){
var texte=''
+ '

'
+ '
'+titol+''
+ '
'+desc+''
+ '
';
return texte;
}
var trackHTML=textTrack("Track no seleccionat","No hi ha informació disponible.");
var trackX=[];
var trackZ=[];
function showTrack(url,titol,kml=true){
messageBox('Carregant el track');
trackHTML="";
var extension=null;
var styleFunction = function (feature) {
var name = feature.get('name');
var tmpext;
if (name == "Dades de la ruta"){ return null;}
if (name != "Consulteu la ruta"){
style = styles['geoMarker'];
if (name!="Path"){
style.getText().setText(name);
} else {
style.getText().setText("");
}
} else {
style =new ol.style.Style({
image: new ol.style.Icon({
anchor: [48, 48],
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
src: MiICO+"info.png?asdjj",
})
})
}
return style;
};
if (zxs == "") closePop();
// Put track
if (kml){
kmlformat=new ol.format.KML({
extractStyles:false,
});
sourceTrack=new ol.source.Vector({
url: url,
format: kmlformat,
});
} else {
gpxformat=new ol.format.GPX({
extractStyles:false,
});
sourceTrack=new ol.source.Vector({
url: url,
format: gpxformat,
});
}
var localtrack = new ol.layer.Vector({
title:titol,
source: sourceTrack,
style: styleFunction,
visible: true,
});
// Necessary because when track is called directly global variable track
// is not accessible inside collectKML (?)
var finished=false;
// Show info
$(document).ready(function () {
if (kml){
$.ajax({
type: "GET",
url: url,
dataType: "xml",
success: collectKML
});
} else {
$.ajax({
type: "GET",
url: url,
dataType: "xml",
success: collectGPX
});
}
});
function collectGPX(gpxDades){
if (!iskml){
$(gpxDades).find("trk").each(function () {
desc=$(this).find('desc').text();
});
} else {
desc=selected.get('description');
}
trackHTML=textTrack(titol,desc);
var coords=[];
var preextension;
preextension=[99999999,99999999,-99999999,-99999999];
var Dist=0;
var Puj=0;
const R=6371;
var latant=-9999;
var lonant=-9999;
var eleant=-9999;
var deg2rad=3.1415926/180.0;
$(gpxDades).find("trkpt").each(function () {
lat=parseFloat($(this).attr('lat'));
lon=parseFloat($(this).attr('lon'));
// ele=parseFloat($(this).find("ele").text());
if (latant == -9999) latant=lat;
if (lonant == -9999) lonant=lon;
// if (eleant == -9999) eleant=ele;
if (lon < preextension[0]) preextension[0]=lon;
if (lon > preextension[2]) preextension[2]=lon;
if (lat < preextension[1]) preextension[1]=lat;
if (lat > preextension[3]) preextension[3]=lat;
/* X=R*Math.cos(lat*deg2rad)*(lon-lonant)*deg2rad;
Y=R*(lat-latant)*deg2rad;
Z=ele-eleant;
Dist=Dist+Math.sqrt(X*X+Y*Y+Z*Z);
trackX.push(Dist);
if (Z>0) Puj+=Z;
trackZ.push(Z);*/
});
// console.log(trackX[trackX.length-1],Puj);
extension=ol.proj.transformExtent(preextension,'EPSG:4326',_projection);
extension[0]-=2000;
extension[1]-=2000;
extension[2]+=2000;
extension[3]+=2000;
map.getView().fit(extension);
var px,py;
px=extension[0]+(extension[2]-extension[0])*0.5;
py=extension[3]-2000;
if (zxs == ""){
var infopoint = new ol.geom.Point([px,py]);
var featureInfo = new ol.Feature({
name: "Consulteu la ruta",
title: "Premeu per consultar la ruta",
geometry: infopoint,
});
sourceTrack.addFeature(featureInfo);
}
closeBox();
finished=true;
return true;
}
function collectKML(kmlDades){
var coords=[];
const regex = /http:/g;
var preextension;
preextension=[99999999,99999999,-99999999,-99999999];
var descA=$(kmlDades).find('description').text().split("");
var desc=descA[0]+"";
if (desc.indexOf("Pujada acumulada")<0) desc=null;
if (desc == null){
desc="No hi ha informació disponible sobre aquest track";
} else {
descA[0]=desc.replace(regex, "https:");
desc=descA[0];
}
trackHTML = textTrack(titol,desc);
$(kmlDades).find("coordinates").each(function () {
coords.push($(this).text());
});
coords.forEach(function(item,index){
let lonlatz=item.split(",");
if (lonlatz[0] < preextension[0]) preextension[0]=lonlatz[0];
if (lonlatz[0] > preextension[2]) preextension[2]=lonlatz[0];
if (lonlatz[1] < preextension[1]) preextension[1]=lonlatz[1];
if (lonlatz[1] > preextension[3]) preextension[3]=lonlatz[1];
});
extension=ol.proj.transformExtent(preextension,'EPSG:4326',_projection);
extension[0]-=2000;
extension[1]-=2000;
extension[2]+=2000;
extension[3]+=2000;
map.getView().fit(extension);
if (zxs !=""){
_center=[0.5*(extension[0]+ extension[2]),0.5*(extension[1]+ extension[3])];
_zoom0=map.getView().getZoom();
}
var px,py;
px=extension[0]+(extension[2]-extension[0])*0.5;
py=extension[3]-2000;
if (zxs == ""){
var infopoint = new ol.geom.Point([px,py]);
var featureInfo = new ol.Feature({
name: "Consulteu la ruta",
title: "Premeu per consultar la ruta",
geometry: infopoint,
});
sourceTrack.addFeature(featureInfo);
}
closeBox();
finished=true;
return true;
}
function waituntilcharged(){
if (finished==true){
track=localtrack;
groupLayersUSER.getLayers().getArray().push(track);
map.addLayer(groupLayersUSER);
track.setVisible(true);
} else {
setTimeout(waituntilcharged, 10); // check ever 0.1 sec
}
}
waituntilcharged(); // Wait until all url have been charged
}
function loadRoutes(type){
var punt;
var estil;
$(document).ready(function () {
$.ajax({
type: "GET",
url:type,
dataType: "xml",
success: collectInfo
});
});
var html_routes=[];
var finished=false;
numberOfRoutes=Routes.length;
function collectInfo(xmlDades){
var i=0;
var totalRoutes=$(xmlDades).find("ruta").length;
$(xmlDades).find("ruta").each(function () {
idruta=$(this).attr('id');
lat=parseFloat($(this).attr('lat'));
lon=parseFloat($(this).attr('lon'));
punt=new ol.geom.Point(ol.proj.transform([lon,lat],'EPSG:4326',_projection));
link = $(this).attr('link');
link_track=$(this).attr('link_track');
titol=$(this).find('titol').text();
descripcio=$(this).find('descripcio').text();
if (idruta<10000){
imatge=MiFOT+idruta+".jpg";
} else {
imatge=MiICO+"banerkml.gif";
}
//Store data into feature for later use...
win="_self";
if (type == _XMLlistWiki) win="_blank";
Rfeatures.push(new ol.Feature({startPoint:true, win:win, geometry: punt,name: idruta, title:titol, description:descripcio, img:imatge, link:link, link_track:link_track}));
sourceRoutes.push(new ol.source.Vector());
sourceRoutes[numberOfRoutes].addFeature(Rfeatures[numberOfRoutes]);
if (type == _XMLlist){
if (i>=totalRoutes-4){
estil=startingPointStyle[totalRoutes-i-1];
html_routes[totalRoutes-i-1] = ''
+ '
'
+ '
'
+ '
'+titol+''
+ '

'
+ '

'
+ '
'+ descripcio + ''
+ '
';
} else {
estil=startingPointStyle[4];
}
} else {
estil=startingPointStyleWiki;
}
Routes.push(new ol.layer.Vector({source:sourceRoutes[numberOfRoutes],name:idruta,style:estil,crossOrigin: 'anonymous', visible: true,}));
//Routes[i].setSource(sourceRoutes[i]);
Routes[numberOfRoutes].setMap(map);
numberOfRoutes++;
i=i+1;
});
if (type == _XMLlist){
var html_darreres = '';
for (j=0;j<4;j++){
html_darreres += html_routes[j];
}
html_darreres += '
';
// Afegim el text a les rutes destacades
document.getElementById("darreres_rutes").innerHTML =html_darreres;
}
finished=true;
return true;
}
function waituntilcharged(){
if (finished==true){
if (type == _XMLlist) {
loadRoutes(_XMLlistWiki);
} else {
map.addEventListener('pointermove',checkRouteInfo);
map.addEventListener('click',showRouteInfo);
}
} else {
setTimeout(waituntilcharged, 10); // check ever 0.1 sec
}
}
waituntilcharged(); // Wait until all url have been charged
}
var overlayTooltip = new ol.Overlay({
element: tooltip,
className: tooltip,
offset: [10, 0],
positioning: 'bottom-left'
});
$('.ol-zoom-in, .ol-zoom-out ').tooltip({
placement: 'right',
container: '#map',
});
$('.ol-rotate-reset, .ol-attribution button[title]').tooltip({
placement: 'left',
container: '#map',
});
function eventFire(el, etype){
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}
// -------------------------------------------------------------------
// init function
// -------------------------------------------------------------------
messageBox("Carregant mapa i rutes");
var titol_globus_punts="";
function CarregaMapa() {
$("#opacity-text").hide();
$("#opacity-bar").hide();
loadMap();
if (zxs!=""){
if (titol_globus_punts==""){
titol_globus_punts="El teu track";
}
closeBox();
if (zxs != "/wp-content/kml_googlemaps/999999_g.kml") {
showTrack(zxs+'?'+Math.random(),'"'+titol_globus_punts+'"',iskml);
}
} else {
loadRoutes(_XMLlist);
closeBox();
}
return;
}