Reverting to 727857606b (before moving to MapBox and ts)

This commit is contained in:
Eric van der Vlist 2025-03-21 14:57:51 +01:00
parent be115b6dd6
commit 26b2ee612f
27 changed files with 68 additions and 60859 deletions

1
.gitignore vendored
View File

@ -3,4 +3,3 @@
################################################################################ ################################################################################
/.vs /.vs
node_modules

View File

@ -6,7 +6,7 @@ Tags: maps, gpx, gps, graph, chart, leaflet, track, garmin, image, nextgen-galle
Requires at least: 6.2.0 Requires at least: 6.2.0
Tested up to: 6.7.1 Tested up to: 6.7.1
Requires PHP: 7.3+ Requires PHP: 7.3+
Stable tag: 1.7.11 Stable tag: 1.7.10
License: GPLv2 or later License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html License URI: https://www.gnu.org/licenses/gpl-2.0.html
@ -197,8 +197,6 @@ Yes!
== Changelog == == Changelog ==
= 1.8.00 =
* MapBox provider: needs ApiKey and brings a lot of new cool features like 3d maps and much more
= 1.7.10 = = 1.7.10 =
* Fix security issues * Fix security issues
= 1.7.06 = = 1.7.06 =

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

BIN
assets/icon-128x128.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

BIN
assets/icon-256x256.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

1
assets/icon.svg Normal file
View File

@ -0,0 +1 @@
<svg height="512pt" viewBox="0 0 512 512" width="512pt" xmlns="http://www.w3.org/2000/svg"><path d="m452 122c-27.601562 0-50 22.402344-50 50v280h100v-280c0-27.609375-22.390625-50-50-50zm0 0" fill="#ececf1"/><path d="m60 122c-27.601562 0-50 22.402344-50 50v280h100c0-10.460938 0-266.328125 0-280 0-27.609375-22.390625-50-50-50zm0 0" fill="#ececf1"/><path d="m260 322h142c0-54.882812 0-108.527344 0-120h-268s91.441406 87.089844 126 120zm0 0" fill="#7fe881"/><path d="m110 262v190c0-27.609375-22.390625-50-50-50s-50 22.390625-50 50c0 29.078125 25.246094 50 52.851562 50h47.148438l126-120zm0 0" fill="#76e2f8"/><path d="m465.320312 403.71875c-33.359374-8.617188-63.320312 16.332031-63.320312 48.28125 0-7.824219 0-35.589844 0-70h-86l-120 120h256c27.621094 0 50-22.378906 50-50 0-24.109375-16.308594-43.019531-36.679688-48.28125zm0 0" fill="#76e2f8"/><path d="m402 322v60h-86l-120 120h-86l126-120-126-120v-60h24s91.441406 87.089844 126 120zm0 0" fill="#fed2a4"/><path d="m256 10c49.710938 0 90 40.289062 90 90 0 24.488281-21.828125 66.089844-43.988281 102-22.832031 37.019531-46.011719 68-46.011719 68s-23.179688-30.980469-46.011719-68c-22.160156-35.910156-43.988281-77.511719-43.988281-102 0-49.710938 40.289062-90 90-90zm0 0" fill="#ff637b"/><path d="m256 60c22.058594 0 40 17.941406 40 40s-17.941406 40-40 40-40-17.941406-40-40 17.941406-40 40-40zm0 0" fill="#ececf1"/><path d="m452 112c-33.144531 0-60 26.847656-60 60v20h-72.3125c24.097656-41.210938 36.3125-72.117188 36.3125-92 0-55.140625-44.859375-100-100-100s-100 44.859375-100 100c0 19.882812 12.214844 50.792969 36.3125 92-8.117188 0-65.292969 0-72.3125 0v-20c0-33.085938-26.914062-60-60-60-33.144531 0-60 26.847656-60 60v56c0 5.523438 4.476562 10 10 10s10-4.476562 10-10v-56c0-22.09375 17.902344-40 40-40 22.054688 0 40 17.945312 40 40v235.316406c-10.621094-9.519531-24.648438-15.316406-40-15.316406-15.355469 0-29.375 5.804688-40 15.328125v-99.328125c0-5.523438-4.476562-10-10-10s-10 4.476562-10 10v144c0 34.308594 29.617188 60 62.851562 60h389.148438c33.085938 0 60-26.914062 60-60v-280c0-33.085938-26.914062-60-60-60zm-40 60c0-22.09375 17.902344-40 40-40 22.054688 0 40 17.945312 40 40v235.042969c-6.875-6.121094-15.152344-10.675781-24.179688-13.003907-20.042968-5.183593-40.664062-.304687-55.820312 13.230469 0-8.550781 0-223.265625 0-235.269531zm-20 140h-128c-33.511719-31.910156-97.515625-92.871094-104.996094-100h45.429688c21.832031 34.875 43.335937 63.691406 43.558594 63.992188 1.890624 2.523437 4.855468 4.007812 8.007812 4.007812s6.117188-1.484375 8.007812-4.007812c.222657-.300782 21.730469-29.117188 43.558594-63.992188h84.433594zm-136-292c44.113281 0 80 35.886719 80 80 0 37.128906-58.570312 122.988281-80 152.988281-21.765625-30.476562-80-116.199219-80-152.988281 0-44.113281 35.886719-80 80-80zm-236 432c0-22.054688 17.945312-40 40-40s40 17.945312 40 40c0 5.523438 4.476562 10 10 10s10-4.476562 10-10v-166.667969l101.5 96.667969-115.5 110h-43.148438c-22.425781 0-42.851562-16.761719-42.851562-40zm222.894531-62.757812c1.984375-1.890626 3.105469-4.507813 3.105469-7.242188s-1.121094-5.355469-3.105469-7.242188l-122.894531-117.042968v-45.714844h10c.683594.652344 118.339844 112.707031 123.105469 117.242188 1.859375 1.769531 4.328125 2.757812 6.894531 2.757812h132v40h-76c-2.652344 0-5.195312 1.054688-7.070312 2.929688l-117.074219 117.070312h-56.855469zm209.105469 102.757812h-231.855469l100-100h71.855469v60c0 5.523438 4.476562 10 10 10s10-4.476562 10-10c0-25.863281 24.21875-45.46875 50.820312-38.597656 16.238282 4.195312 29.179688 19.191406 29.179688 38.597656 0 22.054688-17.945312 40-40 40zm0 0"/><path d="m256 150c27.570312 0 50-22.429688 50-50s-22.429688-50-50-50-50 22.429688-50 50 22.429688 50 50 50zm0-80c16.542969 0 30 13.457031 30 30s-13.457031 30-30 30-30-13.457031-30-30 13.457031-30 30-30zm0 0"/><path d="m10 278c5.519531 0 10-4.480469 10-10s-4.480469-10-10-10-10 4.480469-10 10 4.480469 10 10 10zm0 0"/></svg>

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@ -1,102 +0,0 @@
interface Waypoint {
lat: number;
lon: number;
sym?: string;
type?: string;
img?: string;
name?: string;
desc?: string;
}
interface Params {
targetId: string;
mapType: string;
mapData: any[];
graphDist: any[];
graphEle: any[];
graphSpeed: any[];
graphHr: any[];
graphAtemp: any[];
graphCad: any[];
graphGrade: any[];
waypoints: Waypoint[];
unit: string;
unitspeed: string;
color1: string[];
color2: string;
color3: string;
color4: string;
color5: string;
color6: string;
color7: string;
chartFrom1: string;
chartTo1: string;
chartFrom2: string;
chartTo2: string;
startIcon: string;
waypointIcon: string;
endIcon: string;
currentIcon: string;
zoomOnScrollWheel: string;
langs: any;
pluginUrl: string;
usegpsposition: string;
currentpositioncon: string;
TFApiKey: string;
MapBoxApiKey: string;
MapBoxMapType: string;
MapBoxMapCustomType: string;
MapBox3dTerrain: boolean;
MapBoxFog: boolean;
}
interface LangTranslation {
altitude: string,
currentPosition: string,
speed: string,
grade: string,
heartRate: string,
atemp: string,
cadence: string,
goFullScreen: string,
exitFullFcreen: string,
hideImages: string,
showImages: string,
backToCenter: string
}
interface ChartUom {
suf: string;
dec: number;
}
interface ChartLabels {
label_x: ChartUom;
label_y: ChartUom;
}
type LatLng = [number, number];
interface MapEngine<T> {
map: T | null;
Bounds: Array<number[]> | null;
EventSelectChart: null | Function;
init(targetElement: HTMLElement, mapType: string, scrollWheelZoom: boolean, ApiKey: string | null | undefined, otherParams: any): void;
AppPolylines(mapData: Array<[number, number] | null>, colors: string[], currentIcon: string | null, startIcon: string | null, endIcon: string | null): void;
AddWaypoints(waypoints: any, waypointIcon: string | null): void;
MoveMarkerToPosition(LatLon: [number, number], updateChart: boolean): void;
SetCurrentGPSPosition(LatLon: [number, number], currentpositioncon: string, lng: LangTranslation): void;
AddPhotos(photos: any[]): void;
CenterMap(): void;
}

View File

@ -1,30 +0,0 @@
export const WPGPXMAPS = {
Utils: {
DividePolylinesPoints(mapData: any[]): any[] {
let lastCut = 0;
const result: any[] = [];
const _len = mapData.length;
for (let i = 0; i < _len; i++) {
if (mapData[i] === null) {
result.push(mapData.slice(lastCut === 0 ? 0 : lastCut + 1, i));
lastCut = i;
}
}
if ((_len - 1) !== lastCut) {
result.push(mapData.slice(lastCut));
}
return result;
},
GetItemFromArray(arr: Array<[number,number]|null>, index: number): [number,number] | null {
try {
return arr[index];
} catch (e) {
return [0, 0];
}
}
},
};

View File

@ -1,877 +0,0 @@
/*
Plugin Name: WP-GPX-Maps
Plugin URI: http://www.devfarm.it/
Description: Draws a gpx track with altitude graph
Version: 1.6.02
Author: Bastianon Massimo
Author URI: http://www.devfarm.it/
*/
import './../../css/admin-style.css';
import './../../css/bootstrap-table.css';
import './../../css/wp-gpx-maps-output.css';
import { ActiveElement, Chart, ScaleOptions, LinearScale, ChartConfiguration, registerables, ActiveDataPoint } from 'chart.js'
import { WPGPXMAPS } from './Utils/Utils';
import { LeafletMapEngine } from './maps-engines/LeafletMapEngine';
import { MapBoxMapEngine } from './maps-engines/MapBoxMapEngine';
const wpgpxmaps_FEET_MILES = "1";
const wpgpxmaps_METERS_KILOMETERS = "2";
const wpgpxmaps_METERS_NAUTICALMILES = "3";
const wpgpxmaps_METER_MILES = "4";
const wpgpxmaps_FEET_NAUTICALMILES = "5";
const wpgpxmaps_MINUTES_PER_100METERS = "6";
const wpgpxmaps_KNOTS = "5";
const wpgpxmaps_MINUTES_PER_MILES = "4";
const wpgpxmaps_MINUTES_PER_KM = "3";
const wpgpxmaps_MILES_PER_HOURS = "2";
const wpgpxmaps_KM_PER_HOURS = "1";
export class WPGPXMaps {
private params: Params;
public map : MapEngine<any>|null = null;
public myChart: Chart|null = null;
constructor(params: Params) {
this.params = params;
this.init();
}
private init() {
let {
targetId,
mapType,
mapData,
graphDist,
graphEle,
graphSpeed,
graphHr,
graphAtemp,
graphCad,
graphGrade,
waypoints,
unit,
unitspeed,
color1,
color2,
color3,
color4,
color5,
color6,
color7,
chartFrom1,
chartTo1,
chartFrom2,
chartTo2,
startIcon,
waypointIcon,
endIcon,
currentIcon,
zoomOnScrollWheel,
langs,
pluginUrl,
usegpsposition,
currentpositioncon,
TFApiKey,
} = this.params;
var _formats: ChartLabels[] = [];
/* Unit of measure settings. */
var l_s: ChartUom = { suf: '', dec: 0 };
var label_x: ChartUom = { suf: '', dec: 0 };
var label_y: ChartUom = { suf: '', dec: 0 };
var l_grade: ChartUom = { suf: '%', dec: 1 };
var l_hr: ChartUom = { suf: '', dec: 0 };
var l_cad: ChartUom = { suf: '', dec: 0 };
var el = document.getElementById('wpgpxmaps_' + targetId);
var el_map = document.getElementById('map_' + targetId);
var el_chart = document.getElementById('chart_' + targetId);
var el_report = document.getElementById('report_' + targetId);
var el_osm_credits = document.getElementById('wpgpxmaps_' + targetId + '_osm_footer');
if (el_map == null)
return;
let _this = this;
if (this.params.MapBoxApiKey && this.params.MapBoxApiKey.length>20)
{
this.map = new MapBoxMapEngine();
}
else
{
this.map = new LeafletMapEngine();
}
//map.lng = lng;
this.map.init(
el_map,
mapType,
('true' == zoomOnScrollWheel),
TFApiKey,
this.params
);
this.map.EventSelectChart = function (LatLon: LatLng) {
if (_this.myChart) {
var l1 = LatLon[0];
var l2 = LatLon[1];
var ci = _this.getClosestIndex(mapData, l1, l2);
var activeElements: any[] = [];
var seriesLen = (_this.myChart as any)._metasets.length;
for (var i = 0; i < seriesLen; i++) {
activeElements.push(((_this.myChart as any)._metasets[i] as any).data[ci]);
}
if (activeElements.length > 0) {
let _active = _this.myChart.tooltip?.getActiveElements();
if (_active == undefined || _active.length == 0) {
_this.myChart.tooltip?.setActiveElements([{
datasetIndex: 0,
index: ci,
}], {
x: activeElements[0].x,
y: activeElements[0].y
});
}
(_this.myChart.tooltip as any).setActiveElements(activeElements);
//(_this.myChart.tooltip as any).draw();
_this.myChart.draw();
}
}
};
// var bounds = new google.maps.LatLngBounds();
if ('true' == usegpsposition) {
/* Try HTML5 geolocation. */
if (navigator.geolocation) {
navigator.geolocation.watchPosition(function (position) {
var radius = position.coords.accuracy / 2;
/* User position. */
var pos = [position.coords.latitude, position.coords.longitude];
this.map.SetCurrentGPSPosition([pos[0], pos[1]], currentpositioncon, langs);
},
function (e) {
// Some errors.
},
{
enableHighAccuracy: false,
timeout: 5000,
maximumAge: 0
});
}
}
/* Print WayPoints. */
if (waypoints != null && waypoints.length > 0) {
this.map.AddWaypoints(waypoints, waypointIcon);
}
/* Print Images. */
let nggEl = document.getElementById("ngimages_" + targetId);
nggEl?.setAttribute("style", "display:block;position:absolute;left:-50000px");
var nggImages = nggEl?.querySelectorAll("span");
if (nggImages && nggImages.length > 0) {
var photos = [];
for (var i = 0; i < nggImages.length; i++) {
var ngg_span = nggImages[i];
var ngg_span_a = ngg_span.children[0];
var pos = [
Number(ngg_span.getAttribute('lat')),
Number(ngg_span.getAttribute('lon'))
];
this.map.Bounds.push(pos);
photos.push({
'lat': pos[0],
'lng': pos[1],
'name': ngg_span_a.children[0].getAttribute('alt'),
'image_id': ngg_span_a.getAttribute('data-image-id'),
'url': ngg_span_a.getAttribute('href'),
'thumbnail': ngg_span_a.children[0].getAttribute('src')
});
}
if (photos.length > 0) {
this.map.AddPhotos(photos);
/*
var showHideImagesCustomControl = L.Control.extend({
options: {
position: 'topleft'
//control position - allowed: 'topleft', 'topright', 'bottomleft', 'bottomright'
},
onAdd: function (map) {
var container = document.createElement('img');
container.class= "leaflet-bar leaflet-control leaflet-control-custom"
container.style.backgroundColor = 'white';
container.style.width = '30px';
container.style.height = '30px';
container.src = pluginUrl + "/wp-gpx-maps/img/hideImages.png";
container.style.cursor = 'pointer';
container.title = lng.hideImages;
container.onclick = function(){
var isImagesHidden = (controlUIhi.isImagesHidden == true);
var mapDiv = map.getDiv();
var center = map.getCenter();
if (isImagesHidden)
{
for (var i=0; i<ngImageMarkers.length; i++) {
ngImageMarkers[i].setMap(map);
}
controlUIhi.src = pluginUrl + "/wp-gpx-maps/img/hideImages.png";
controlUIhi.title = lng.hideImages;
}
else
{
for (var i=0; i<ngImageMarkers.length; i++) {
ngImageMarkers[i].setMap(null);
}
controlUIhi.src = pluginUrl + "/wp-gpx-maps/img/showImages.png";
controlUIhi.title = lng.showImages;
}
controlUIhi.isImagesHidden = !isImagesHidden;
return false;
}
return container;
},
});
map.map.addControl(new showHideImagesCustomControl());
*/
}
}
/*
// Nextgen Pro Lightbox FIX
var _xx = jQuery("#ngimages_" + targetId + " .nextgen_pro_lightbox");
if (_xx.length > 0)
{
var rnd1 = Math.random().toString(36).substring(7);
var rnd2 = Math.random().toString(36).substring(7);
//get first gallery without images
for (var _temp in galleries) {
var _gal = galleries[_temp];
if (_gal.source == "random_images" && _gal.wpgpxmaps != true )
{
_gal.source == "galleries";
_gal.wpgpxmaps = true;
_transient_id = _temp.replace("gallery_","")
_gal["entity_ids"] = [];
_gal["image_ids"] = [];
_gal["gallery_ids"] = [96];
for (var i=0;i<_xx.length;i++)
{
var __xx = jQuery(_xx[i]);
__xx.attr("data-nplmodal-gallery-id", _transient_id);
_gal["image_ids"].push(__xx.attr("data-image-id"));
}
break;
}
}
}
*/
/* Print Track. */
if (mapData) {
this.map.AppPolylines(mapData, color1, currentIcon, startIcon, endIcon);
}
/*
map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
*/
var contextMap = this.map;
// Fix post tabs. */
let _tab: HTMLElement | null = null;
let _p = el?.parentElement;
while (_p != null) {
if (_p.classList.contains("wordpress-post-tabs") && _p.classList.contains("tab-pane")) {
_tab = _p;
break;
}
_p = _p.parentElement;
}
if (_tab) {
var tabResized = false;
var FixMapSize = function (e: any) {
setTimeout(function (e: any) {
// google.maps.event.trigger(map, 'resize');
contextMap.map?.invalidateSize();
contextMap.CenterMap();
tabResized = true;
}, 300);
};
document.querySelector(".wpsm_nav-tabs a")?.addEventListener("click", FixMapSize, false);
_tab.querySelector("div > ul > li > a")?.addEventListener("click", FixMapSize, false);
}
var graphh = el_chart?.style.height;
if (graphDist && (graphEle || graphSpeed || graphHr || graphAtemp || graphCad) && graphh != '0px') {
var valLen = graphDist.length;
if (wpgpxmaps_FEET_MILES == unit) {
/* feet / miles */
label_x = { suf: 'mi', dec: 1 };
label_y = { suf: 'ft', dec: 0 };
} else if (wpgpxmaps_METERS_KILOMETERS == unit) {
/* meters / kilometers */
label_x = { suf: 'km', dec: 1 };
label_y = { suf: 'm', dec: 2 };
} else if (wpgpxmaps_METERS_NAUTICALMILES == unit) {
/* meters / nautical miles */
label_x = { suf: 'NM', dec: 1 };
label_y = { suf: 'm', dec: 0 };
} else if (wpgpxmaps_METER_MILES == unit) {
/* meters / miles */
label_x = { suf: 'mi', dec: 1 };
label_y = { suf: 'm', dec: 0 };
} else if (wpgpxmaps_FEET_NAUTICALMILES == unit) {
/* feet / nautical miles */
label_x = { suf: 'NM', dec: 1 };
label_y = { suf: 'ft', dec: 0 };
} else {
/* meters / meters */
label_x = { suf: 'm', dec: 0 };
label_y = { suf: 'm', dec: 0 };
}
var nn = 1111.1;
var _nn = nn.toLocaleString();
var _nnLen = _nn.length;
var decPoint = _nn.substring(_nnLen - 2, _nnLen - 1);
var thousandsSep = _nn.substring(1, 2);
if ('1' == decPoint)
decPoint = '.';
if ('1' == thousandsSep)
thousandsSep = '';
// trik per caricare tutti imoduli di chart.js
Chart.register(...registerables);
/* Define the options. */
var hoptions: ChartConfiguration = {
type: 'line',
data: {
datasets: []
},
//borderWidth: 1,
options: {
animation: {
// duration: 0,
// general animation time
},
hover: {
// animationDuration: 0,
// duration of animations when hovering an item
},
interaction: {
intersect: false,
mode: 'index',
},
// responsiveAnimationDuration: 0,
// animation duration after a resize
//customLine: {
// color: 'gray'
//},
scales: {
xAxe: {
type: 'linear',
min: 0,
max: graphDist[graphDist.length - 1],
ticks: {
/* Include a dollar sign in the ticks. */
callback: function (value, index, values) {
return parseFloat(value + "").toFixed(label_x.dec) + label_x.suf;
}
}
}
},
plugins: {
tooltip: {
position: 'average',
mode: 'index',
intersect: false,
callbacks: {
title: function (tooltipItems) {
/* Return value for title: */
var label_x = _formats[0].label_x;
var x_pos = tooltipItems[0].element.x as number;
var x_dec = label_x.dec;
var x_unit = label_x.suf;
return x_pos.toFixed(x_dec) + x_unit;
},
label: function (tooltipItem) {
/* Format list values: */
var label = tooltipItem.label || '';
var label_y = _formats[tooltipItem.datasetIndex].label_y;
var y_dec = label_y.dec;
var y_unit = label_y.suf;
var y_pos = tooltipItem.element.y as number;
if (label) {
label += ': ';
}
label += y_pos.toFixed(y_dec) + y_unit;
return label;
},
footer: function (tooltipItem: any) {
/* Move the point in map. */
var i = tooltipItem[0].dataIndex;
var point = WPGPXMAPS.Utils.GetItemFromArray(mapData, i);
if (point)
contextMap.MoveMarkerToPosition(point, false);
}
}
},
/*
decimation: {
beforeEvent: function (chart, args, options) {
if ((args.event.type === 'mousemove' && args.event.x)
&& (args.event.x >= chart.chartArea.left)
&& (args.event.x <= chart.chartArea.right)
) {
chart.options.customLine.x = args.event.x;
}
},
afterDraw: function (chart, args, opt) {
var ctx = chart.ctx;
var chartArea = chart.chartArea;
var x = chart.options.customLine.x;
if (!isNaN(x)) {
ctx.save();
ctx.strokeStyle = chart.options.customLine.color;
ctx.moveTo(chart.options.customLine.x, chartArea.bottom);
ctx.lineTo(chart.options.customLine.x, chartArea.top);
ctx.stroke();
ctx.restore();
}
}
}
*/
},
},
//labels: graphDist
};
let yAxeCount = 1;
if (graphEle && graphEle.length > 0) {
var myData = this.mergeArrayForChart(graphDist, graphEle);
let _min: number, _max: number
if (chartFrom1 != '') {
_min = parseFloat(chartFrom1);
//yaxe.startOnTick = false;
} else {
_min = myData.Min;
}
if (chartTo1 != '') {
_max = parseFloat(chartTo1);
//yaxe.endOnTick = false;
} else {
_max = myData.Max;
}
var _id = 'yaxis' + yAxeCount++;
var yaxe: ScaleOptions = {
type: 'linear',
max: _max,
min: _min,
ticks: {
callback(tickValue, index, ticks) {
return parseFloat(tickValue + "").toFixed(label_y.dec) + label_y.suf;
}
},
};
(hoptions.options?.scales as any)[_id] = yaxe;
_formats.push({ "label_x": label_x, "label_y": label_y });
hoptions.data.datasets.push(this.wpgpxmapsGetDataset(langs.altitude, myData.Items, color2, _id));
}
if (graphSpeed && graphSpeed.length > 0) {
if (wpgpxmaps_MINUTES_PER_100METERS == unitspeed) {
/* min/100 meters */
l_s = { suf: 'min/100m', dec: 2 };
} else if (wpgpxmaps_KNOTS == unitspeed) {
/* knots */
l_s = { suf: 'knots', dec: 2 };
} else if (wpgpxmaps_MINUTES_PER_MILES == unitspeed) {
/* min/miles */
l_s = { suf: 'min/mi', dec: 2 };
} else if (wpgpxmaps_MINUTES_PER_KM == unitspeed) {
/* min/km */
l_s = { suf: 'min/km', dec: 2 };
} else if (wpgpxmaps_MILES_PER_HOURS == unitspeed) {
/* miles/h */
l_s = { suf: 'mi/h', dec: 0 };
} else if (wpgpxmaps_KM_PER_HOURS == unitspeed) {
/* km/h */
l_s = { suf: 'km/h', dec: 0 };
} else {
/* dafault m/s */
l_s = { suf: 'm/s', dec: 0 };
}
var myData = this.mergeArrayForChart(graphDist, graphSpeed);
let yaxe: ScaleOptions = {
type: 'linear',
ticks: {
/* Include a dollar sign in the ticks. */
callback(tickValue, index, ticks) {
return parseFloat(tickValue + "").toFixed(l_s.dec) + l_s.suf;
}
},
position: 'right',
//scalePositionLeft: false,
};
if (chartFrom2 != '') {
yaxe.min = parseFloat(chartFrom2);
//yaxe.startOnTick = false;
} else {
yaxe.min = myData.Min;
}
if (chartTo2 != '') {
yaxe.max = parseFloat(chartTo2);
//yaxe.endOnTick = false;
} else {
yaxe.max = myData.Max;
}
_formats.push( { label_x: _formats[0].label_x , label_y : l_s});
var _id = 'yaxis' + yAxeCount++;
(hoptions.options?.scales as any)[_id] = yaxe;
hoptions.data.datasets.push(this.wpgpxmapsGetDataset(langs.speed, myData.Items, color3, _id));
}
if (graphHr && graphHr.length > 0) {
var myData = this.mergeArrayForChart(graphDist, graphHr);
var yaxe: ScaleOptions = {
type: 'linear',
ticks: {
/* Include a dollar sign in the ticks. */
callback(tickValue, index, ticks) {
return parseFloat(tickValue + "").toFixed(l_hr.dec) + l_hr.suf;
}
},
position: 'right',
//scalePositionLeft: false,
};
var _id = 'yaxis' + yAxeCount++;
(hoptions.options?.scales as any)[_id] = yaxe;
hoptions.data.datasets.push(this.wpgpxmapsGetDataset(langs.heartRate, myData.Items, color4, _id));
_formats.push( { label_x: _formats[0].label_x , label_y : l_hr});
}
if (graphAtemp && graphAtemp.length > 0) {
var myData = this.mergeArrayForChart(graphDist, graphAtemp);
var yaxe: ScaleOptions = {
type: 'linear',
ticks: {
/* Include a dollar sign in the ticks. */
callback(tickValue, index, ticks) {
return parseFloat(tickValue + "").toFixed(1) + "°C";
}
},
position: 'right',
//scalePositionLeft: false,
};
var _id = 'yaxis' + yAxeCount++;
(hoptions.options?.scales as any)[_id] = yaxe;
hoptions.data.datasets.push(this.wpgpxmapsGetDataset(langs.atemp, myData.Items, color7, _id));
_formats.push( { label_x: _formats[0].label_x , label_y : { suf: '°C', dec: 1 }});
}
if (graphCad && graphCad.length > 0) {
var myData = this.mergeArrayForChart(graphDist, graphCad, true);
var yaxe: ScaleOptions = {
type: 'linear',
ticks: {
// Include a dollar sign in the ticks.
callback(tickValue, index, ticks) {
return parseFloat(tickValue + "").toFixed(l_cad.dec) + l_cad.suf;
}
},
position: 'right',
//scalePositionLeft: false,
};
var _id = 'yaxis' + yAxeCount++;
(hoptions.options?.scales as any)[_id] = yaxe;
hoptions.data.datasets.push(this.wpgpxmapsGetDataset(langs.cadence, myData.Items, color5, _id));
_formats.push( { label_x: _formats[0].label_x , label_y : l_cad});
}
if (graphGrade && graphGrade.length > 0) {
var myData = this.mergeArrayForChart(graphDist, graphGrade);
var yaxe : ScaleOptions = {
type: 'linear',
ticks: {
// Include a dollar sign in the ticks.
callback: function (value, index, values) {
return parseFloat(value+"").toFixed(l_grade.dec) + l_grade.suf;
}
},
position: 'right',
//scalePositionLeft: false,
};
_formats.push( { label_x: _formats[0].label_x , label_y : l_grade});
var _id = 'yaxis' + yAxeCount++;
(hoptions.options?.scales as any)[_id] = yaxe;
hoptions.data.datasets.push(this.wpgpxmapsGetDataset(langs.grade, myData.Items, color6, _id));
}
var ctx = (document.getElementById('myChart_' + targetId) as HTMLCanvasElement)?.getContext('2d');
if (ctx)
this.myChart = new Chart(ctx, hoptions);
} else {
el_chart?.style.setProperty("display", "none");
}
return this;
};
private mergeArrayForChart(distArr: any[], dataArr: any[], setZerosAsNull?: boolean) {
const l = distArr.length;
const items = new Array(l);
let min = 10000;
let max = -10000;
for (let i = 0; i < l; i++) {
if (distArr[i] != null) {
let _item = dataArr[i];
if (setZerosAsNull === true && _item === 0) {
_item = null;
}
items[i] = {
x: distArr[i],
y: _item
};
if (_item > max) max = _item;
if (_item < min) min = _item;
}
}
return {
Items: items,
Min: min,
Max: max
};
}
private wpgpxmapsGetDataset(name: string, data: any[], color: string, id: string) {
return {
label: name,
data: data,
borderColor: color,
backgroundColor: this.hexToRgbA(color, 0.3),
pointRadius: 0,
borderWidth: 1,
pointHoverRadius: 1,
yAxisID: id
};
}
private hexToRgbA(hex: string, a: number) {
let c: any;
if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
c = hex.substring(1).split('');
if (c.length == 3) {
c = [c[0], c[0], c[1], c[1], c[2], c[2]];
}
c = '0x' + c.join('');
return 'rgba(' + [(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',') + ',' + a + ')';
}
throw new Error('Bad Hex');
}
private getItemFromArray(arr: any[], index: number) {
try {
return arr[index];
} catch (e) {
return [0, 0];
}
}
private getClosestIndex(points: any[], lat: number, lon: number) {
let dd = 10000;
let ii = 0;
for (let i = 0; i < points.length; i++) {
if (points[i] === null) continue;
const d = this.wpgpxmapsDist(points[i][0], points[i][1], lat, lon);
if (d < dd) {
ii = i;
dd = d;
}
}
return ii;
}
private getClosestImage(lat: number, lon: number, targetId: string) {
let dd = 10000;
let img;
const divImages = document.getElementById("ngimages_" + targetId);
if (divImages == null)
return;
const img_spans = divImages.getElementsByTagName("span");
for (let i = 0; i < img_spans.length; i++) {
let imageLat = img_spans[i].getAttribute('lat');
let imageLon = img_spans[i].getAttribute('lon');
if (imageLat == null || imageLon == null)
return;
imageLat = imageLat.replace(",", ".");
imageLon = imageLon.replace(",", ".");
const d = this.wpgpxmapsDist(parseFloat(imageLat), parseFloat(imageLon), lat, lon);
if (d < dd) {
img = img_spans[i];
dd = d;
}
}
return img;
}
private isNumeric(input: string) {
const RE = /^-{0,1}\d*\.{0,1}\d+$/;
return RE.test(input);
}
private wpgpxmapsDist(lat1: number, lon1: number, lat2: number, lon2: number) {
const dLat = (lat2 - lat1);
const dLon = (lon2 - lon1);
return Math.sqrt(dLat * dLat + dLon * dLon);
}
}

View File

@ -1,601 +0,0 @@
import L, { Layer, Map, Marker, Polyline, Polygon } from 'leaflet';
import 'leaflet.fullscreen/Control.FullScreen.js';
import 'leaflet.fullscreen';
import 'leaflet.markercluster';
import { WPGPXMAPS } from '../Utils/Utils';
import 'leaflet.markercluster/dist/MarkerCluster.css';
import 'leaflet/dist/leaflet.css';
import 'leaflet.fullscreen/Control.FullScreen.css';
class ClusterPhotos {
map: Map | null = null;
shownLayer: Layer | null = null;
polygon: Polygon | null = null;
markers: any | null = null;
options: {
icon: {
iconSize: [40, 40],
},
};
constructor(map: Map) {
this.map = map;
//Custom radius and icon create function
this.markers = (L as any).markerClusterGroup({
maxClusterRadius: 120,
iconCreateFunction: function (cluster) {
return new L.DivIcon(
L.extend(
{
className: "leaflet-marker-photo",
html:
'<div style="background-image: url(' +
cluster.getAllChildMarkers()[0].photo.thumbnail +
');"></div><b>' +
cluster.getChildCount() +
"</b>",
},
this.icon
)
);
},
//Disable all of the defaults:
spiderfyOnMaxZoom: false, showCoverageOnHover: false, zoomToBoundsOnClick: false
});
this.markers.on('click', function (evt: any) {
var photo = evt.layer.photo;
var template = '<img src="{url}" /></a><p>{name}</p>';
evt.layer.bindPopup(L.Util.template(template, photo), {
minWidth: 'auto'
}).openPopup();
});
this.markers.on('clustermouseover', function (a) {
this.removePolygon();
a.layer.setOpacity(0.2);
this.shownLayer = a.layer;
this.polygon = L.polygon(a.layer.getConvexHull());
this.map.addLayer(this.polygon);
});
this.markers.on('clustermouseout', this.removePolygon);
this.map.on('zoomend', this.removePolygon);
this.map.addLayer(this.markers);
}
populate(images: any[]) {
for (const photo of images) {
var m = L.marker(L.latLng(photo.lat, photo.lng), {
icon: L.divIcon(
L.extend(
{
html:
'<div style="background-image: url(' +
photo.thumbnail +
');"></div>',
className: "leaflet-marker-photo",
},
photo,
{
iconSize: [40, 40],
}
)
),
title: photo.caption || "",
});
this.markers.addLayer(m);
}
return false;
}
private removePolygon() {
if (this.shownLayer) {
(this.shownLayer as any).setOpacity(1);
this.shownLayer = null;
}
if (this.polygon) {
this.map.removeLayer(this.polygon);
this.polygon = null;
}
};
}
export class LeafletMapEngine implements MapEngine<Map> {
Bounds: Array<number[]> = [];
lng: LangTranslation | null = null;
map: Map | null = null;
EventSelectChart: null | Function = null;
Polylines: Array<Polyline> = [];
CurrentPositionMarker: Marker | null = null;
CurrentGPSPositionMarker: Marker | null = null;
constructor() {
}
init(targetElement: HTMLElement, mapType: string, scrollWheelZoom: boolean, ThunderforestApiKey: string | null | undefined, otherParams: any): void {
this.map = L.map(targetElement,
{
scrollWheelZoom: scrollWheelZoom
}
);
// create fullscreen control.
var fsControl = new (L as any).Control.FullScreen();
// Add fullscreen control to the map.
this.map.addControl(fsControl);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(this.map);
var hasThunderforestApiKey = (ThunderforestApiKey + '').length > 0;
var baseMaps: any = {};
var overlayMaps = {};
var defaultMpaLayer = null;
if (hasThunderforestApiKey) {
/* Map type: Thunderforest - OpenCycleMap with API key */
baseMaps['Thunderforest - Cycle'] = L.tileLayer('https://a.tile.thunderforest.com/cycle/{z}/{x}/{y}.png?apikey=' + ThunderforestApiKey, {
maxZoom: 18,
attribution: 'Maps &copy; <a href="https://www.thunderforest.com/">Thunderforest</a> contributors, ' +
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>'
});
} else {
/* Map type: Open Cycle Map - Cycle */
baseMaps['Open Cycle Map'] = L.tileLayer('http://a.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Maps &copy; <a href="https://www.thunderforest.com/">Thunderforest</a> contributors, ' +
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>'
});
}
/* Map type: Thunderforest - Outdoors with API key */
baseMaps['Thunderforest - Outdoors'] = L.tileLayer('https://a.tile.thunderforest.com/outddors/{z}/{x}/{y}.png?apikey=' + ThunderforestApiKey, {
maxZoom: 18,
attribution: 'Maps &copy; <a href="https://www.thunderforest.com/">Thunderforest</a> contributors, ' +
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>'
});
/* Map type: Thunderforest - Transport with API key */
baseMaps['Thunderforest - Transport'] = L.tileLayer('https://a.tile.thunderforest.com/transport/{z}/{x}/{y}.png?apikey=' + ThunderforestApiKey, {
maxZoom: 18,
attribution: 'Maps &copy; <a href="https://www.thunderforest.com/">Thunderforest</a> contributors, ' +
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>'
});
/* Map type: Thunderforest - Landscape with API key */
baseMaps['Thunderforest - Landscape'] = L.tileLayer('https://a.tile.thunderforest.com/landscape/{z}/{x}/{y}.png?apikey=' + ThunderforestApiKey, {
maxZoom: 18,
attribution: 'Maps &copy; <a href="https://www.thunderforest.com/">Thunderforest</a> contributors, ' +
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>'
});
/* Map type: Open Street Map */
baseMaps['Open Street Map'] = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Maps &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>'
});
///* Map type: MapToolKit - Terrain */
//baseMaps['MapToolKit - Terrain'] = L.tileLayer( 'https://tile2.maptoolkit.net/terrain/{z}/{x}/{y}.png', {
// maxZoom: 18,
// attribution: 'Maps &copy; <a href="https://www.maptoolkit.net/">Maptoolkit</a> contributors, ' +
// '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
// 'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>'
//});
/* Map type: Open Street Map - Humanitarian Map Style */
baseMaps['Humanitarian Map Style'] = L.tileLayer('https://a.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Maps &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>'
});
/*
Map type: Open Ski Map
baseMaps['Open Ski Map'] = L.tileLayer( 'http://tiles.skimap.org/openskimap/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
});
*/
/* Map type: Hike & Bike */
baseMaps['Hike & Bike'] = L.tileLayer('http://toolserver.org/tiles/hikebike/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Maps &copy; <a href="https://hikebikemap.org/">Hike & Bike Map</a> contributors, ' +
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>'
});
/* Map type: Open Sea Map */
baseMaps['Open Sea Map'] = L.tileLayer('http://tiles.openseamap.org/seamark/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Maps &copy; <a href="https://www.openseamap.org/">OpenSeaMap</a> contributors, ' +
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>'
});
baseMaps['GSI Map (Japan)'] = L.tileLayer('https://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: '&copy; <a href="https://maps.gsi.go.jp/development/ichiran.html" target="_blank">国土地理院</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>'
});
switch (mapType) {
/* Map type: Open Street Map */
case 'OSM1': {
baseMaps['Open Street Map'].addTo(this.map);
break;
}
/* Map type: Thunderforest - Open Cycle Maps with API key */
case 'OSM2': {
baseMaps['Thunderforest - Cycle'].addTo(this.map);
break;
}
/* Map type: Thunderforest - Outdoors with API key */
case 'OSM3': {
baseMaps['Thunderforest - Outdoors'].addTo(this.map);
break;
}
/* Map type: Thunderforest - Landscape with API key */
case 'OSM4': {
baseMaps['Thunderforest - Transport'].addTo(this.map);
break;
}
/* Map type: Thunderforest - Landscape with API key */
case 'OSM5': {
baseMaps['Thunderforest - Landscape'].addTo(this.map);
break;
}
///* Map type: MapToolKit - Terrain */
//case 'OSM6': {
// baseMaps['MapToolKit - Terrain'].addTo( this.map );
// break;
//}
/* Map type: Open Street Map - Humanitarian Map Style*/
case 'OSM7': {
baseMaps['Humanitarian Map Style'].addTo(this.map);
break;
}
/*
Map type: Open Ski Map
case 'OSM8': {
baseMaps['Open Ski Map'].addTo( this.map );
break;
}
*/
/* Map type: Hike & Bike */
case 'OSM9': {
baseMaps['Hike & Bike'].addTo(this.map);
break;
}
/* Map type: Open Sea Map */
case 'OSM10': {
baseMaps['Open Sea Map'].addTo(this.map);
break;
}
case 'OSM11': {
baseMaps['GSI Map (Japan)'].addTo(this.map);
break;
}
/* Map type: Open Street Map */
default: {
baseMaps['Open Street Map'].addTo(this.map);
}
}
L.control.layers(baseMaps, overlayMaps).addTo(this.map);
}
AppPolylines(mapData: Array<[number, number] | null>, colors: string[], currentIcon: string | null, startIcon: string | null, endIcon: string | null): void {
if (null == this.map) {
return;
}
var first = WPGPXMAPS.Utils.GetItemFromArray(mapData, 0);
if (null == first) {
return;
}
if ('' == currentIcon || null == currentIcon) {
currentIcon = 'https://maps.google.com/mapfiles/kml/pal4/icon25.png';
}
var CurrentPositionMarker = L.marker(L.latLng(first), {
icon: L.icon({
iconUrl: currentIcon,
iconSize: [32, 32], // Size of the icon.
iconAnchor: [16, 16] // Point of the icon which will correspond to marker's location.
}),
title: this.lng?.currentPosition
});
CurrentPositionMarker.addTo(this.map);
this.CurrentPositionMarker = CurrentPositionMarker;
var pointsArray = WPGPXMAPS.Utils.DividePolylinesPoints(mapData);
var lng = this.lng;
var EventSelectChart = this.EventSelectChart;
this.Bounds = mapData.filter(o => o != null);
this.CenterMap();
for (let i = 0; i < pointsArray.length; i++) {
let color = '';
if (i < colors.length) {
color = colors[i];
} else {
color = colors[colors.length - 1];
}
try {
let polyline = L.polyline(pointsArray[i], { color: color }).addTo(this.map);
this.Polylines.push(polyline);
let context = this;
this.Polylines[i].on('mousemove', function (e: any) {
context.MoveMarkerToPosition([e.latlng.lat, e.latlng.lng], true);
});
} catch (err) {
}
}
if (startIcon != '') {
let ll = mapData[0];
if (ll != null) {
let startMarker = L.marker(L.latLng(ll), {
icon: L.icon({
iconUrl: startIcon + "",
iconSize: [32, 32], // Size of the icon.
iconAnchor: [16, 16] // Point of the icon which will correspond to marker's location.
}),
title: 'Start'
});
startMarker.addTo(this.map);
}
}
if (endIcon != '' && mapData[mapData.length - 1] != null) {
let ll = mapData[mapData.length - 1];
if (ll != null) {
var endMarker = L.marker(L.latLng(ll), {
icon: L.icon({
iconUrl: endIcon + "",
iconSize: [32, 32], // size of the icon
iconAnchor: [16, 16] // point of the icon which will correspond to marker's location
}),
title: 'End'
});
endMarker.addTo(this.map);
}
}
}
SetCurrentGPSPosition(pos: [number, number], currentpositioncon: string, lng: LangTranslation): void {
if (null == this.CurrentGPSPositionMarker) {
if ('' == currentpositioncon) {
currentpositioncon = 'https://maps.google.com/mapfiles/kml/pal4/icon25.png';
}
if (this.map != null) {
this.CurrentGPSPositionMarker = L.marker(pos, {
icon: L.icon({
iconUrl: currentpositioncon,
iconSize: [32, 32], // Size of the icon.
iconAnchor: [16, 16] // Point of the icon which will correspond to marker's location.
})
})
.addTo(this.map)
.bindPopup(lng.currentPosition)
.openPopup();
}
} else {
this.CurrentGPSPositionMarker.setLatLng(pos);
}
this.Bounds.push(pos);
this.CenterMap();
}
AddWaypoints(waypoints: any, waypointIcon: string | null): void {
var icon = L.icon({
iconUrl: 'https://maps.google.com/mapfiles/ms/micons/flag.png',
iconSize: [32, 32], // Size of the icon.
iconAnchor: [16, 16] // Point of the icon which will correspond to marker's location.
});
if (waypointIcon != '') {
icon = L.icon({
iconUrl: 'waypointIcon',
iconSize: [32, 32], // Size of the icon.
iconAnchor: [16, 16] // Point of the icon which will correspond to marker's location.
});
}
for (let i = 0; i < waypoints.length; i++) {
var wpt = waypoints[i];
this.Bounds.push([wpt.lat, wpt.lon]);
var lat = wpt.lat;
var lon = wpt.lon;
var sym = wpt.sym;
var typ = wpt.type;
if (wpt.img) {
(icon as any).iconUrl = wpt.img + "";
//wsh = '';
}
var marker = L.marker([lat, lon], { icon: icon });
var cnt = '';
if (wpt.name == '') {
cnt = "<div>" + unescape(wpt.desc) + "</div>";
} else {
cnt = "<div><b>" + wpt.name + "</b><br />" + unescape(wpt.desc) + "</div>";
}
cnt += "<br /><p><a href='https://maps.google.com?daddr=" + lat + "," + lon + "' target='_blank'>Itin&eacute;raire</a></p>";
if (this.map != null)
marker.addTo(this.map).bindPopup(cnt);
}
this.CenterMap();
}
MoveMarkerToPosition(LatLon: [number, number], updateChart: boolean): void {
if (null == this.CurrentPositionMarker)
return;
this.CurrentPositionMarker.setLatLng(LatLon);
if (this.lng)
this.CurrentPositionMarker.setTooltipContent(this.lng.currentPosition);
//this.CurrentPositionMarker.title = this.lng.currentPosition;
if (true == updateChart && this.EventSelectChart)
this.EventSelectChart(LatLon);
}
CenterMap(): void {
try {
if (this.Bounds && this.Bounds.length > 0) {
let bounds = {
minLat: Number.POSITIVE_INFINITY,
maxLat: Number.NEGATIVE_INFINITY,
minLng: Number.POSITIVE_INFINITY,
maxLng: Number.NEGATIVE_INFINITY
};
this.Bounds.forEach(coord => {
if (!Array.isArray(coord) || coord.length !== 2) {
throw new Error("Each coordinate must be an array with [latitude, longitude].");
}
const [lat, lng] = coord;
bounds.minLat = Math.min(bounds.minLat, lat);
bounds.maxLat = Math.max(bounds.maxLat, lat);
bounds.minLng = Math.min(bounds.minLng, lng);
bounds.maxLng = Math.max(bounds.maxLng, lng);
});
var southWest = new L.LatLng(bounds.minLat, bounds.minLng),
northEast = new L.LatLng(bounds.maxLat, bounds.maxLng);
this.map?.fitBounds(new L.LatLngBounds(southWest, northEast));
}
} catch (error) {
console.log(error);
}
}
AddPhotos(photos: any[]): void {
for (const photo of photos) {
let m = L.marker(photo, {
icon: L.divIcon(
L.extend(
{
html:
'<div style="background-image: url(' +
photo.thumbnail +
');"></div>',
className: "leaflet-marker-photo",
},
photo,
{
iconSize: [40, 40],
}
)
),
title: photo.caption || "",
});
m.bindPopup('<img src="' + photo.url + '" /></a><p>' + photo.name + '</p>', { minWidth: 500 });
m.addTo(this.map);
//this.map.addLayer(m);
}
//new ClusterPhotos(this.map).populate(photos)
}
}
export default LeafletMapEngine;

View File

@ -1,458 +0,0 @@
import { WPGPXMAPS } from '../Utils/Utils';
import { MapboxStyleDefinition, MapboxStyleSwitcherOptions, MapboxStyleSwitcherControl } from "mapbox-gl-style-switcher";
import mapboxgl, { ControlPosition, GeoJSONSource, IControl, LngLatBounds, Map, Marker } from 'mapbox-gl';
import * as turf from '@turf/turf';
import 'mapbox-gl/dist/mapbox-gl.css';
import "mapbox-gl-style-switcher/styles.css";
class AnumationControl implements IControl {
container: HTMLElement;
start: number = 0.0;
animationDuration: number = 80000;
cameraAltitude: number = 1000;
targetRoute: Array<number[]> = [];
cameraRoute: Array<number[]> = [];
map: Map;
iconDefault: string = '/wp-content/plugins/wp-gpx-maps/img/map-play-svgrepo-com.svg';
iconStop: string = '/wp-content/plugins/wp-gpx-maps/img/stop-svgrepo-com.svg';
routeDistance: number = 0.0;
cameraRouteDistance: number = 0.0;
isPlaying: boolean = false;
onAdd(map: Map): HTMLElement {
this.map = map;
this.container = document.createElement('div');
this.container.className = 'mapboxgl-ctrl mapboxgl-ctrl-group mapboxgl-wp-gpx-maps';
this.container.innerHTML = `<button style='background-image: url(${this.iconDefault});'>&nbsp;</div>`;
this.container.onclick = () => {
// Your custom logic here
if (this.isPlaying == false) {
this.isPlaying = true;
this._playAnimation();
}
else {
this.isPlaying = false;
}
};
return this.container;
}
_animationFrame(time) {
if (this.isPlaying == false) {
this.start = 0.0;
return;
}
if (!this.start) this.start = time;
// phase determines how far through the animation we are
const phase = (time - this.start) / this.animationDuration;
// phase is normalized between 0 and 1
// when the animation is finished, reset start to loop the animation
if (phase > 1) {
// wait 1.5 seconds before looping
setTimeout(() => {
this.start = 0.0;
}, 1500);
}
// use the phase to get a point that is the appropriate distance along the route
// this approach syncs the camera and route positions ensuring they move
// at roughly equal rates even if they don't contain the same number of points
const alongRoute = turf.along(
turf.lineString(this.targetRoute),
this.routeDistance * phase
).geometry.coordinates;
const alongCamera = turf.along(
turf.lineString(this.cameraRoute),
this.cameraRouteDistance * phase
).geometry.coordinates;
const camera = this.map.getFreeCameraOptions();
// set the position and altitude of the camera
camera.position = mapboxgl.MercatorCoordinate.fromLngLat(
{
lng: alongCamera[0],
lat: alongCamera[1]
},
this.cameraAltitude
);
// tell the camera to look at a point along the route
camera.lookAtPoint({
lng: alongRoute[0],
lat: alongRoute[1]
});
this.map.setFreeCameraOptions(camera);
window.requestAnimationFrame((time) => this._animationFrame(time));
}
_stopAnimation() {
}
_playAnimation() {
this.cameraRouteDistance = turf.lineDistance(
turf.lineString(this.cameraRoute)
);
this.routeDistance = turf.lineDistance(
turf.lineString(this.targetRoute)
);
window.requestAnimationFrame((time) => this._animationFrame(time));
}
onRemove(map: Map) {
this.container.remove();
}
getDefaultPosition?: () => ControlPosition;
_setLanguage?: (language?: string | string[]) => void;
}
export class MapBoxMapEngine implements MapEngine<Map> {
map: Map;
Bounds: Array<number[]> = [];
EventSelectChart: null | Function = null;
CurrentLocationMarker: mapboxgl.Marker | null = null;
animationControl: AnumationControl | null = null;
otherParams: any;
animateLineOptions: any = {
SpeedFactor: 30, // number of frames per longitude degree
Animation: null, // to store and cancel the animation
StartTime: 0,
Progress: 0, // progress = timestamp - startTime
ResetTime: false // indicator of whether time reset is needed for the animation
}
init(targetElement: HTMLElement, mapType: string, scrollWheelZoom: boolean, MapBoxApiKey: string | null | undefined, otherParams: any): void {
this.otherParams = otherParams;
this.map = new mapboxgl.Map({
container: targetElement,
style: 'mapbox://styles/mapbox/streets-v11',
accessToken: "pk.eyJ1Ijoic2VjdXJjdWJlbWF4IiwiYSI6ImNsbW94MzRodjE4YjEya3BuM3liZXl6MXYifQ.db3c6nnAcFwFm5jD2NCg6w", // MapBoxApiKey ??
center: [0, 0],
zoom: 1,
scrollZoom: scrollWheelZoom
});
this.animationControl = new AnumationControl();
this.map.addControl(new mapboxgl.NavigationControl());
this.map.addControl(new mapboxgl.FullscreenControl());
const styles: MapboxStyleDefinition[] = [
{ uri: 'mapbox://styles/mapbox/standard', title: 'Standard' },
{ uri: 'mapbox://styles/mapbox/standard-satellite', title: 'Standard Satelite' },
{ uri: 'mapbox://styles/mapbox/streets-v12', title: 'Streets' },
{ uri: 'mapbox://styles/mapbox/outdoors-v12', title: 'Outdoors' },
{ uri: 'mapbox://styles/mapbox/light-v11', title: 'Light' },
{ uri: 'mapbox://styles/mapbox/dark-v11', title: 'Dark' },
{ uri: 'mapbox://styles/mapbox/satellite-v9', title: 'Satellite' },
{ uri: 'mapbox://styles/mapbox/satellite-streets-v12', title: 'Satellite Streets' },
{ uri: 'mapbox://styles/mapbox/navigation-day-v1', title: 'Navigation Day' },
{ uri: 'mapbox://styles/mapbox/navigation-night-v1', title: 'Navigation Night' }
];
// Pass options (optional)
const options: MapboxStyleSwitcherOptions = {
defaultStyle: "Satellite Streets",
eventListeners: {
// return true if you want to stop execution
// onOpen: (event: MouseEvent) => boolean;
// onSelect: (event: MouseEvent) => boolean;
// onChange: (event: MouseEvent, style: string) => boolean;
}
};
this.map.addControl(new MapboxStyleSwitcherControl() as IControl, 'top-left');
this.map.addControl(this.animationControl);
this.map.on('style.load', async () => {
if (otherParams.MapBoxFog) {
// Add daytime fog
this.map.setFog({
'range': [-1, 2],
'horizon-blend': 0.3,
'color': 'white',
'high-color': '#add8e6',
'space-color': '#d8f2ff',
'star-intensity': 0.0
});
}
if (otherParams.MapBox3dTerrain) {
// 3d terrain
this.map.addSource('mapbox-dem', {
'type': 'raster-dem',
'url': 'mapbox://mapbox.mapbox-terrain-dem-v1',
'tileSize': 512,
'maxzoom': 14
});
// add the DEM source as a terrain layer with exaggerated height
this.map.setTerrain({ 'source': 'mapbox-dem', 'exaggeration': 1.5 });
}
});
}
_addMarker(ll: [number, number], icon: string | null, popup: Function | null): Marker {
// Create a DOM element for each marker.
const el = document.createElement('div');
const width = 32;
const height = 32;
el.className = 'marker';
el.style.backgroundImage = `url(${icon})`;
el.style.width = `${width}px`;
el.style.height = `${height}px`;
el.style.backgroundSize = '100%';
el.addEventListener('click', (e) => {
popup?.call(this, e);
});
return new mapboxgl.Marker(el).setLngLat([ll[1], ll[0]]).addTo(this.map);
}
AppPolylines(mapData: Array<[number, number] | null>, colors: string[], currentIcon: string | null, startIcon: string | null, endIcon: string | null): void {
this.Bounds = mapData.filter(o => o != null);
this.map.on('style.load', async () => {
const pointsArray = WPGPXMAPS.Utils.DividePolylinesPoints(mapData);
const LngLatRute = this.Bounds.map((point) => [point[1], point[0]]);
this.animationControl.cameraRoute = LngLatRute;
this.animationControl.targetRoute = LngLatRute;
this.map.addSource('route', {
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': pointsArray.map((points, i) => {
return ({
'type': 'Feature',
'properties': {
color: (i < colors.length ? colors[i] : colors[colors.length - 1])
},
'geometry': {
'type': 'LineString',
'coordinates': points.map((point) => [point[1], point[0]])
}
});
})
}
});
this.map.addLayer({
'id': 'route',
'type': 'line',
'source': 'route',
'layout': {
'line-join': 'round',
'line-cap': 'round'
},
'paint': {
'line-color': ['get', 'color'],
'line-width': 3
}
});
if ('' == currentIcon || null == currentIcon) {
currentIcon = 'https://maps.google.com/mapfiles/kml/pal4/icon25.png';
}
this.CurrentLocationMarker = this._addMarker(mapData[0], currentIcon, (e) => {
});
if (startIcon != '') {
let ll = mapData[0];
if (ll != null) {
this._addMarker(ll, startIcon, null);
}
}
if (endIcon != '' && mapData[mapData.length - 1] != null) {
let ll = mapData[mapData.length - 1];
if (ll != null) {
this._addMarker(ll, endIcon, null);
}
}
this.CenterMap();
if (this.otherParams.MapBoxAnimateOnLoading == '1') {
this.animateLineOptions.StartTime = performance.now();
this.animateLine();
}
});
}
AddWaypoints(waypoints: any, waypointIcon: string | null): void {
//throw new Error('Method not implemented.');
}
MoveMarkerToPosition(LatLon: [number, number], updateChart: boolean): void {
this.CurrentLocationMarker?.setLngLat([LatLon[1], LatLon[0]]);
//throw new Error('Method not implemented.');
}
SetCurrentGPSPosition(LatLon: [number, number], currentpositioncon: string, lng: LangTranslation): void {
///throw new Error('Method not implemented.');
}
CenterMap(): void {
try {
if (this.Bounds && this.Bounds.length > 0) {
let bounds = {
minLat: Number.POSITIVE_INFINITY,
maxLat: Number.NEGATIVE_INFINITY,
minLng: Number.POSITIVE_INFINITY,
maxLng: Number.NEGATIVE_INFINITY
};
this.Bounds.forEach(coord => {
if (!Array.isArray(coord) || coord.length !== 2) {
throw new Error("Each coordinate must be an array with [latitude, longitude].");
}
const [lat, lng] = coord;
bounds.minLat = Math.min(bounds.minLat, lat);
bounds.maxLat = Math.max(bounds.maxLat, lat);
bounds.minLng = Math.min(bounds.minLng, lng);
bounds.maxLng = Math.max(bounds.maxLng, lng);
});
const sw = new mapboxgl.LngLat(bounds.minLng, bounds.minLat);
const ne = new mapboxgl.LngLat(bounds.maxLng, bounds.maxLat);
this.map?.fitBounds(new mapboxgl.LngLatBounds(sw, ne), { padding: 30, animate: false });
}
} catch (error) {
console.log(error);
}
//throw new Error('Method not implemented.');
}
AddPhotos(photos: any[]): void {
const width = 40;
const height = 40;
for (const photo of photos) {
let _m = this._addMarker([photo.lat, photo.lng], photo.thumbnail, (e) => {
let _selector = `a[data-image-id='${photo.image_id}']`;
let galleryEl = document.querySelector(_selector);
(galleryEl as HTMLAnchorElement)?.click()
});
_m._element.classList.add('wp-gpx-maps-photo-marker');
_m._element.style.width = `${width}px`;
_m._element.style.height = `${height}px`;
//_m.setPopup(new mapboxgl.Popup({ maxWidth: "900px"}).setHTML(`<img src='${photo.url}' alt='${photo.name}' />`));
}
//new ClusterPhotos(this.map).populate(photos)
}
// animated in a circle as a sine wave along the map.
animateLine(timestamp: number | null = null) {
if (timestamp == null) {
// fist call
var geojson = (this.map.getSource('route') as GeoJSONSource)._data;
this.animateLineOptions.ruteJeoJson = geojson;
this.animateLineOptions.ruteCoordinates = (geojson as any).features[0].geometry.coordinates;
(geojson as any).features[0].geometry.coordinates = [];
}
if (this.animateLineOptions.ResetTime) {
// resume previous progress
this.animateLineOptions.sta = performance.now() - this.animateLineOptions.Progress;
this.animateLineOptions.ResetTime = false;
} else {
this.animateLineOptions.Progress = timestamp - this.animateLineOptions.StartTime;
}
if (this.animateLineOptions.Progress < 0)
this.animateLineOptions.Progress = 0;
// restart if it finishes a loop
if (this.animateLineOptions.Progress > this.animateLineOptions.SpeedFactor * 360) {
this.animateLineOptions.startTime = timestamp;
// stop the animation
return;
} else {
let len = this.animateLineOptions.ruteCoordinates.length;
let slice = Math.floor(len * this.animateLineOptions.Progress / (this.animateLineOptions.SpeedFactor * 360));
this.animateLineOptions.ruteJeoJson.features[0].geometry.coordinates =
this.animateLineOptions.ruteCoordinates.slice(0, slice);
// then update the map
var s = (this.map.getSource('route') as GeoJSONSource).setData(this.animateLineOptions.ruteJeoJson);
}
// Request the next frame of the animation.
this.animateLineOptions.animation = requestAnimationFrame((time) => this.animateLine(time));
}
}

View File

@ -61,37 +61,3 @@
background: #fff; background: #fff;
vertical-align: baseline; vertical-align: baseline;
} }
.wpgpxmaps .leaflet-marker-photo {
border: 2px solid #fff;
box-shadow: 3px 3px 10px #888;
}
.wpgpxmaps .leaflet-marker-photo div {
width: 100%;
height: 100%;
background-size: cover;
background-position: center center;
background-repeat: no-repeat;
}
.wpgpxmaps .leaflet-marker-photo b {
position: absolute;
top: -7px;
right: -11px;
color: #555;
background-color: #fff;
border-radius: 8px;
height: 12px;
min-width: 12px;
line-height: 12px;
text-align: center;
padding: 3px;
box-shadow: 0 3px 14px rgba(0,0,0,0.4);
}
.mapboxgl-wp-gpx-maps{
background-size: contain;
background-repeat: no-repeat;
}

View File

@ -1,2 +0,0 @@
<?xml version="1.0" encoding="utf-8"?><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
<svg width="800px" height="800px" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--gis" preserveAspectRatio="xMidYMid meet"><path d="M65.809 5a2.5 2.5 0 0 0-1.03.232L34.166 19.453L3.553 5.233A2.5 2.5 0 0 0 0 7.5v70.29a2.5 2.5 0 0 0 1.447 2.267l31.666 14.71A2.5 2.5 0 0 0 34.19 95a2.5 2.5 0 0 0 1.032-.232l30.613-14.221l30.613 14.22A2.5 2.5 0 0 0 100 92.5V22.21a2.5 2.5 0 0 0-1.447-2.267L66.887 5.233A2.5 2.5 0 0 0 65.809 5zm1.142 5.775L95 23.805v64.777L67.322 75.725l-.37-64.95zm-2.998.354l.37 64.605l-28.677 13.323l-.369-64.606L63.953 11.13zM5 11.418l27.275 12.67l.371 64.95L5 76.192V11.418z" fill="#000000" fill-rule="evenodd"></path><path d="M50 24a26 26 0 0 0-26 26a26 26 0 0 0 26 26a26 26 0 0 0 26-26a26 26 0 0 0-26-26zm-6.979 9.502a1.526 1.5 0 0 1 1 .299l20.348 15a1.526 1.5 0 0 1 0 2.398l-20.348 15A1.526 1.5 0 0 1 41.581 65V35a1.526 1.5 0 0 1 1.44-1.498z" fill="#000000"></path></svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
<svg fill="#000000" width="800px" height="800px" viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">
<title>stop</title>
<path d="M5.92 24.096q0 0.832 0.576 1.408t1.44 0.608h16.128q0.832 0 1.44-0.608t0.576-1.408v-16.16q0-0.832-0.576-1.44t-1.44-0.576h-16.128q-0.832 0-1.44 0.576t-0.576 1.44v16.16z"></path>
</svg>

Before

Width:  |  Height:  |  Size: 450 B

View File

@ -893,9 +893,9 @@ var WPGPXMAPS = {
photos.push({ photos.push({
'lat': pos[0], 'lat': pos[0],
'lng': pos[1], 'lng': pos[1],
'name': ngg_span_a.getAttribute( 'data-title' ), 'name': ngg_span_a.children[0].getAttribute( 'alt' ),
'url': ngg_span_a.getAttribute('data-src'), 'url': ngg_span_a.children[0].getAttribute( 'src' ),
'thumbnail': ngg_span_a.getAttribute('data-thumbnail') 'thumbnail': ngg_span_a.children[0].getAttribute( 'src' )
}); });
} }

3531
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,24 +0,0 @@
{
"name": "wp-gpx-maps",
"version": "1.0.0",
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview"
},
"dependencies": {
"@turf/turf": "^6.5.0",
"chart.js": "^4.4.7",
"leaflet": "^1.9.4",
"leaflet.fullscreen": "^3.0.2",
"leaflet.markercluster": "^1.5.3",
"mapbox-gl": "^3.9.4",
"mapbox-gl-style-switcher": "^1.0.11"
},
"devDependencies": {
"@types/leaflet": "^1.9.16",
"@types/leaflet.fullscreen": "^3.0.2",
"typescript": "^4.0.0",
"vite": "^4.0.0"
}
}

View File

@ -1,18 +0,0 @@
{
"compilerOptions": {
"target": "ES5",
"module": "CommonJS",
"moduleResolution": "node",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"lib": ["ESNext", "es5", "es6", "DOM"],
"types" : ["node"],
},
"include": [
"assets/src/@types/types.ts",
"assets/src/*.ts",
"assets/src/**/*.ts"
],
"exclude": ["node_modules"]
}

View File

@ -1,17 +0,0 @@
import { defineConfig } from 'vite';
import { resolve } from "path";
export default defineConfig({
build: {
outDir: 'assets/dist',
sourcemap: true,
lib: {
entry: resolve(__dirname, "assets/src/WP-GPX-Maps.ts"),
name: "WPGPXMaps",
fileName: (format) => `WP-GPX-Maps.${format}.js`,
formats: ["es", "umd"],
},
}
});

View File

@ -34,15 +34,6 @@ $total_time = get_option( 'wpgpxmaps_summary_total_time' );
$t = get_option( 'wpgpxmaps_map_type' ); $t = get_option( 'wpgpxmaps_map_type' );
$zoomonscrollwheel = get_option( 'wpgpxmaps_zoomonscrollwheel' ); $zoomonscrollwheel = get_option( 'wpgpxmaps_zoomonscrollwheel' );
$showW = get_option( 'wpgpxmaps_show_waypoint' ); $showW = get_option( 'wpgpxmaps_show_waypoint' );
/* MapBox */
$mapbox3dTerrain = get_option( 'wpgpxmaps_mapbox_3dterrain' );
$mapboxMapType = get_option( 'wpgpxmaps_mapbox_type' );
$mapboxCustomMapType = get_option( 'wpgpxmaps_mapbox_customtype' );
$mapboxFog = get_option( 'wpgpxmaps_mapbox_fog' );
$mapboxLoadAnimation = get_option( 'wpgpxmaps_mapbox_load_animation');
/* Diagram */ /* Diagram */
$showEle = get_option( 'wpgpxmaps_show_elevation' ); $showEle = get_option( 'wpgpxmaps_show_elevation' );
$uom = get_option( 'wpgpxmaps_unit_of_measure' ); $uom = get_option( 'wpgpxmaps_unit_of_measure' );
@ -188,7 +179,7 @@ function render_select($name, $label, $options, $selected) {
<?php <?php
render_radio('wpgpxmaps_map_type', 'Default map type:', [ render_radio('wpgpxmaps_map_type', 'Default map type:', [
'OSM1' => 'Open Street Map', 'OSM1' => 'Open Street Map',
'OSM2' => 'Open Cycle Map / Thunderforest - Open Cycle Map (API Key required)', 'OSM2' => 'Open Cycle Map / Thunderforest - Open Cycle Map (API Key required)',
'OSM3' => 'Thunderforest - Outdoors (API Key required)', 'OSM3' => 'Thunderforest - Outdoors (API Key required)',
@ -199,31 +190,7 @@ function render_select($name, $label, $options, $selected) {
'OSM9' => 'Hike & Bike', 'OSM9' => 'Hike & Bike',
'OSM10' => 'Open Sea Map', 'OSM10' => 'Open Sea Map',
'OSM11' => 'GSI Map (Japan)' 'OSM11' => 'GSI Map (Japan)'
], $t); ], $t);
render_radio('wpgpxmaps_mapbox_type', 'MapBox default style:', [
'standard' => 'Standard',
'standard-satellite' => 'Standard Satelite',
'streets-v12' => 'Streets',
'outdoors-v12' => 'Outdoors',
'light-v11' => 'Light',
'dark-v11' => 'Dark',
'satellite-v9' => 'Satellite',
'satellite-streets-v12' => 'Satellite Streets',
'navigation-day-v1' => 'Navigation Day',
'navigation-night-v1' => 'Navigation Night'
], $mapboxMapType);
render_text_input('wpgpxmaps_mapbox_customtype', 'Custom MapBox style:', $mapboxCustomMapType, 'width:400px;');
render_radio('wpgpxmaps_mapbox_load_animation', 'MapBox animation on load:', [
'0' => 'Disabled',
'1' => 'Draw line from start to end',
], $mapboxLoadAnimation);
render_checkbox('wpgpxmaps_mapbox_3dterrain', 'MapBox 3d terrain:', $mapbox3dTerrain);
render_checkbox('wpgpxmaps_mapbox_fog', 'MapBox fog:', $mapboxFog);
render_text_input('wpgpxmaps_map_line_color', 'Map line color:', get_option('wpgpxmaps_map_line_color'), 'width:100px;'); render_text_input('wpgpxmaps_map_line_color', 'Map line color:', get_option('wpgpxmaps_map_line_color'), 'width:100px;');
render_checkbox('wpgpxmaps_zoomonscrollwheel', 'On mouse scroll wheel:', $zoomonscrollwheel); render_checkbox('wpgpxmaps_zoomonscrollwheel', 'On mouse scroll wheel:', $zoomonscrollwheel);
render_checkbox('wpgpxmaps_show_waypoint', 'Waypoints support:', $showW); render_checkbox('wpgpxmaps_show_waypoint', 'Waypoints support:', $showW);
@ -237,7 +204,7 @@ function render_select($name, $label, $options, $selected) {
<p class="submit"> <p class="submit">
<input type="hidden" name="action" value="update" /> <input type="hidden" name="action" value="update" />
<input name="page_options" type="hidden" value="wpgpxmaps_mapbox_load_animation,wpgpxmaps_mapbox_customtype,wpgpxmaps_mapbox_fog,wpgpxmaps_mapbox_type,wpgpxmaps_mapbox_3dterrain,wpgpxmaps_map_type,wpgpxmaps_map_line_color,wpgpxmaps_zoomonscrollwheel,wpgpxmaps_show_waypoint,wpgpxmaps_map_start_icon,wpgpxmaps_map_end_icon,wpgpxmaps_map_current_icon,wpgpxmaps_currentpositioncon,wpgpxmaps_map_waypoint_icon" /> <input name="page_options" type="hidden" value="wpgpxmaps_map_type,wpgpxmaps_map_line_color,wpgpxmaps_zoomonscrollwheel,wpgpxmaps_show_waypoint,wpgpxmaps_map_start_icon,wpgpxmaps_map_end_icon,wpgpxmaps_map_current_icon,wpgpxmaps_currentpositioncon,wpgpxmaps_map_waypoint_icon" />
<input type="submit" class="button-primary" value="<?php esc_html_e( 'Save Changes', 'wp-gpx-maps' ); ?>" /> <input type="submit" class="button-primary" value="<?php esc_html_e( 'Save Changes', 'wp-gpx-maps' ); ?>" />
</p> </p>
</form> </form>

View File

@ -1,6 +1,7 @@
<?php <?php
function wpgpxmaps_isNGGalleryActive() { function wpgpxmaps_isNGGalleryActive() {
if ( ! function_exists( 'is_plugin_active' ) ) { if ( ! function_exists( 'is_plugin_active' ) ) {
require_once( wp_gpx_maps_sitePath() . '/wp-admin/includes/plugin.php' ); require_once( wp_gpx_maps_sitePath() . '/wp-admin/includes/plugin.php' );
} }
@ -8,13 +9,13 @@ function wpgpxmaps_isNGGalleryActive() {
} }
function wpgpxmaps_isNGGalleryProActive() { function wpgpxmaps_isNGGalleryProActive() {
if ( ! function_exists( 'is_plugin_active' ) ) { if ( ! function_exists( 'is_plugin_active' ) ) {
require_once( wp_gpx_maps_sitePath() . '/wp-admin/includes/plugin.php' ); require_once( wp_gpx_maps_sitePath() . '/wp-admin/includes/plugin.php' );
} }
return is_plugin_active( 'nextgen-gallery-pro/nggallery-pro.php' ); return is_plugin_active( 'nextgen-gallery-pro/nggallery-pro.php' );
} }
function getNGGalleryImages( $ngGalleries, $ngImages, $dt, $lat, $lon, $dtoffset, &$error ) { function getNGGalleryImages( $ngGalleries, $ngImages, $dt, $lat, $lon, $dtoffset, &$error ) {
$result = array(); $result = array();
@ -32,8 +33,6 @@ function getNGGalleryImages( $ngGalleries, $ngImages, $dt, $lat, $lon, $dtoffset
array_push( $pictures, nggdb::find_image( $i ) ); array_push( $pictures, nggdb::find_image( $i ) );
} }
//print_r($pictures);
foreach ( $pictures as $p ) { foreach ( $pictures as $p ) {
if (!is_object($p)) if (!is_object($p))
@ -49,7 +48,6 @@ function getNGGalleryImages( $ngGalleries, $ngImages, $dt, $lat, $lon, $dtoffset
$exif = @exif_read_data( $imagePath ); $exif = @exif_read_data( $imagePath );
if ( $exif !== false && is_array($exif) && sizeof($exif) > 0 ) { if ( $exif !== false && is_array($exif) && sizeof($exif) > 0 ) {
//print_r($exif); //print_r($exif);
$GPSLongitude = 0; $GPSLongitude = 0;
@ -90,11 +88,12 @@ function getNGGalleryImages( $ngGalleries, $ngImages, $dt, $lat, $lon, $dtoffset
} catch (Exception $e) { } catch (Exception $e) {
//$error .= "Sorry, <a href='https://php.net/manual/en/function.exif-read-data.php' target='_blank' rel='noopener noreferrer'>exif_read_data</a> function not found! check your hosting.<br />"; //$error .= "Sorry, <a href='https://php.net/manual/en/function.exif-read-data.php' target='_blank' rel='noopener noreferrer'>exif_read_data</a> function not found! check your hosting.<br />";
} }
} }
/* START FIX NEXT GEN GALLERY 2.x */ /* START FIX NEXT GEN GALLERY 2.x */
if ( class_exists( 'C_Displayed_Gallery_Renderer' ) ) { if ( class_exists( 'C_Component_Registry' ) ) {
$renderer = C_Displayed_Gallery_Renderer::get_instance(); $renderer = C_Component_Registry::get_instance()->get_utility( 'I_Displayed_Gallery_Renderer' );
$params['gallery_ids'] = $ngGalleries; $params['gallery_ids'] = $ngGalleries;
$params['image_ids'] = $ngImages; $params['image_ids'] = $ngImages;
$params['display_type'] = NEXTGEN_GALLERY_BASIC_THUMBNAILS; $params['display_type'] = NEXTGEN_GALLERY_BASIC_THUMBNAILS;
@ -114,15 +113,10 @@ function getNGGalleryImages( $ngGalleries, $ngImages, $dt, $lat, $lon, $dtoffset
} }
/* END FIX NEXT GEN GALLERY PRO */ /* END FIX NEXT GEN GALLERY PRO */
} }
else
{
echo "no C_Displayed_Gallery_Renderer ";
}
/* END FIX NEXT GEN GALLERY 2.x */ /* END FIX NEXT GEN GALLERY 2.x */
} catch ( Exception $e ) { } catch ( Exception $e ) {
$error .= $e->getMessage(); $error .= 'Error When Retrieving NextGen Gallery galleries/images: $e <br />';
$error .= "Error When Retrieving NextGen Gallery galleries/images: $e ";
} }
return $result; return $result;
} }

View File

@ -376,12 +376,7 @@ function wpgpxmaps_parseXml( $filePath, $gpxOffset, $distancetype ) {
$_ele = array_filter( $points->ele ); $_ele = array_filter( $points->ele );
$_dist = array_filter( $points->dist ); $_dist = array_filter( $points->dist );
if (count($_dist) > 0) if ($_ele) {
{
$points->totalLength = max( $_dist );
}
if (count($_ele) > 0) {
/* /*
There might be cases where ele is not set in the gpx (0.00). There might be cases where ele is not set in the gpx (0.00).
array_filter will filter out those values and as a consequence min()/max() would fail. array_filter will filter out those values and as a consequence min()/max() would fail.
@ -390,16 +385,9 @@ function wpgpxmaps_parseXml( $filePath, $gpxOffset, $distancetype ) {
$points->minEle = min( $_ele ); $points->minEle = min( $_ele );
} }
if (count($_time) > 0) $points->totalLength = max( $_dist );
{ $points->maxTime = max( $_time );
$points->maxTime = max( $_time ); $points->minTime = min( $_time );
$points->minTime = min( $_time );
}
else
{
$points->maxTime = null;
$points->minTime = null;
}
/* Calculating Average Speed */ /* Calculating Average Speed */
$_speed = array_filter( $points->speed ); $_speed = array_filter( $points->speed );

View File

@ -3,7 +3,7 @@
* Plugin Name: WP-GPX-Maps * Plugin Name: WP-GPX-Maps
* Plugin URI: http://www.devfarm.it/ * Plugin URI: http://www.devfarm.it/
* Description: Draws a GPX track with altitude chart * Description: Draws a GPX track with altitude chart
* Version: 1.8.00 * Version: 1.7.10
* Author: Bastianon Massimo * Author: Bastianon Massimo
* Author URI: http://www.devfarm.it/ * Author URI: http://www.devfarm.it/
* Text Domain: wp-gpx-maps * Text Domain: wp-gpx-maps
@ -18,7 +18,7 @@
/** /**
* Version of the plugin * Version of the plugin
*/ */
define( 'WPGPXMAPS_CURRENT_VERSION', '1.8.00' ); define( 'WPGPXMAPS_CURRENT_VERSION', '1.7.06' );
require 'wp-gpx-maps-utils.php'; require 'wp-gpx-maps-utils.php';
require 'wp-gpx-maps-admin.php'; require 'wp-gpx-maps-admin.php';
@ -83,6 +83,13 @@ function wpgpxmaps_action_links( $links, $file ) {
function wpgpxmaps_enqueue_scripts_admin( $hook ) { function wpgpxmaps_enqueue_scripts_admin( $hook ) {
if ( strpos( $hook, 'WP-GPX-Maps' ) !== false ) { if ( strpos( $hook, 'WP-GPX-Maps' ) !== false ) {
/* Admin Style CSS */
wp_register_style( 'admin-style', plugins_url( 'css/admin-style.css', __FILE__ ), array(), '1.0.0' );
wp_enqueue_style( 'admin-style' );
/* mColorPicker */
wp_register_script( 'mColorPicker', plugins_url( '/js/mColorPicker_min.js', __FILE__ ), array(), '1.0 r39' );
wp_enqueue_script( 'mColorPicker' );
/* bootstrap-table */ /* bootstrap-table */
wp_register_script( 'bootstrap-table', plugins_url( '/js/bootstrap-table.js', __FILE__ ), array(), '1.13.2' ); wp_register_script( 'bootstrap-table', plugins_url( '/js/bootstrap-table.js', __FILE__ ), array(), '1.13.2' );
wp_enqueue_script( 'bootstrap-table' ); wp_enqueue_script( 'bootstrap-table' );
@ -114,59 +121,44 @@ function downloadRemoteFile( $file_url ) {
function wpgpxmaps_enqueue_scripts() { function wpgpxmaps_enqueue_scripts() {
if (false) /* Output Style CSS */
{ wp_register_style( 'output-style', plugins_url( 'css/wp-gpx-maps-output.css', __FILE__ ), array(), '1.0.0' );
wp_enqueue_style( 'output-style' );
/* Output Style CSS */ /* Leaflet */
wp_register_style( 'output-style', plugins_url( 'css/wp-gpx-maps-output.css', __FILE__ ), array(), '1.0.0' ); wp_register_style( 'leaflet', plugins_url( '/ThirdParties/Leaflet_1.5.1/leaflet.css', __FILE__ ), array(), '1.5.1' );
wp_enqueue_style( 'output-style' ); wp_enqueue_style( 'leaflet' );
/* Leaflet */ /* Leaflet.markercluster */
wp_register_style( 'leaflet', plugins_url( '/ThirdParties/Leaflet_1.5.1/leaflet.css', __FILE__ ), array(), '1.5.1' ); wp_register_style( 'leaflet.markercluster', plugins_url( '/ThirdParties/Leaflet.markercluster-1.4.1/MarkerCluster.css', __FILE__ ), array(), '1.4.1,' );
wp_enqueue_style( 'leaflet' ); wp_enqueue_style( 'leaflet.markercluster' );
/* Leaflet.markercluster */ /* Leaflet.Photo */
wp_register_style( 'leaflet.markercluster', plugins_url( '/ThirdParties/Leaflet.markercluster-1.4.1/MarkerCluster.css', __FILE__ ), array(), '1.4.1,' ); wp_register_style( 'leaflet.Photo', plugins_url( '/ThirdParties/Leaflet.Photo/Leaflet.Photo.css', __FILE__ ), array(), '0' );
wp_enqueue_style( 'leaflet.markercluster' ); wp_enqueue_style( 'leaflet.Photo' );
/* Leaflet.Photo */ /* Leaflet.fullscreen */
wp_register_style( 'leaflet.Photo', plugins_url( '/ThirdParties/Leaflet.Photo/Leaflet.Photo.css', __FILE__ ), array(), '0' ); wp_register_style( 'leaflet.fullscreen', plugins_url( '/ThirdParties/leaflet.fullscreen-1.4.5/Control.FullScreen.css', __FILE__ ), array(), '1.5.1' );
wp_enqueue_style( 'leaflet.Photo' ); wp_enqueue_style( 'leaflet.fullscreen' );
/* Leaflet.fullscreen */ wp_register_script( 'leaflet', plugins_url( '/ThirdParties/Leaflet_1.5.1/leaflet.js', __FILE__ ), array(), '1.5.1' );
wp_register_style( 'leaflet.fullscreen', plugins_url( '/ThirdParties/leaflet.fullscreen-1.4.5/Control.FullScreen.css', __FILE__ ), array(), '1.5.1' ); wp_register_script( 'leaflet.markercluster', plugins_url( '/ThirdParties/Leaflet.markercluster-1.4.1/leaflet.markercluster.js', __FILE__ ), array( 'leaflet' ), '1.4.1' );
wp_enqueue_style( 'leaflet.fullscreen' ); wp_register_script( 'leaflet.Photo', plugins_url( '/ThirdParties/Leaflet.Photo/Leaflet.Photo.js', __FILE__ ), array( 'leaflet', 'leaflet.markercluster' ), '0' );
wp_register_script( 'leaflet.fullscreen', plugins_url( '/ThirdParties/leaflet.fullscreen-1.4.5/Control.FullScreen.js', __FILE__ ), array( 'leaflet' ), '1.4.5' );
wp_register_script( 'leaflet', plugins_url( '/ThirdParties/Leaflet_1.5.1/leaflet.js', __FILE__ ), array(), '1.5.1' ); /* Chartjs */
wp_register_script( 'leaflet.markercluster', plugins_url( '/ThirdParties/Leaflet.markercluster-1.4.1/leaflet.markercluster.js', __FILE__ ), array( 'leaflet' ), '1.4.1' ); wp_register_script( 'chartjs', plugins_url( '/js/Chart.min.js', __FILE__ ), array(), '2.8.0' );
wp_register_script( 'leaflet.Photo', plugins_url( '/ThirdParties/Leaflet.Photo/Leaflet.Photo.js', __FILE__ ), array( 'leaflet', 'leaflet.markercluster' ), '0' );
wp_register_script( 'leaflet.fullscreen', plugins_url( '/ThirdParties/leaflet.fullscreen-1.4.5/Control.FullScreen.js', __FILE__ ), array( 'leaflet' ), '1.4.5' );
/* Chartjs */ wp_register_script( 'wp-gpx-maps', plugins_url( 'js/WP-GPX-Maps.js', __FILE__ ), array( 'jquery', 'leaflet', 'chartjs' ), '1.6.02' );
wp_register_script( 'chartjs', plugins_url( '/js/Chart.min.js', __FILE__ ), array(), '2.8.0' );
wp_register_script( 'wp-gpx-maps', plugins_url( 'js/WP-GPX-Maps.js', __FILE__ ), array( 'jquery', 'leaflet', 'chartjs' ), '1.6.02' ); wp_enqueue_script( 'output-style' );
wp_enqueue_script( 'leaflet' );
wp_enqueue_script( 'output-style' ); wp_enqueue_script( 'leaflet.markercluster' );
wp_enqueue_script( 'leaflet' ); wp_enqueue_script( 'leaflet.Photo' );
wp_enqueue_script( 'leaflet.markercluster' ); wp_enqueue_script( 'leaflet.fullscreen' );
wp_enqueue_script( 'leaflet.Photo' ); wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'leaflet.fullscreen' ); wp_enqueue_script( 'chartjs' );
wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'wp-gpx-maps' );
wp_enqueue_script( 'chartjs' );
wp_enqueue_script( 'wp-gpx-maps' );
}
else
{
/* Output Style CSS */
wp_register_style( 'output-style', plugins_url( 'assets/dist/style.css', __FILE__ ), array(), '1.0.0' );
wp_enqueue_style( 'output-style' );
wp_register_script_module( 'wp-gpx-maps', plugins_url( 'assets/dist/WP-GPX-Maps.es.js', __FILE__ ), array(), '1.6.02' );
wp_enqueue_script_module( 'wp-gpx-maps' );
}
} }
@ -260,7 +252,7 @@ function wpgpxmaps_handle_folder_shortcodes( $attr, $content = '' ) {
} }
} }
//print_r( $points ); print_r( $points );
} }
} }
@ -344,8 +336,7 @@ function wpgpxmaps_handle_shortcodes( $attr, $content = '' ) {
} else { } else {
$mtime = 0; $mtime = 0;
} }
//$cacheFileName = "$gpx,$mtime,$w,$mh,$mt,$gh,$showEle,$showW,$showHr,$showAtemp,$showCad,$donotreducegpx,$pointsoffset,$showSpeed,$showGrade,$unit_of_measure_speed,$unit_of_measure,$distanceType,v1.3.9"; $cacheFileName = "$gpx,$mtime,$w,$mh,$mt,$gh,$showEle,$showW,$showHr,$showAtemp,$showCad,$donotreducegpx,$pointsoffset,$showSpeed,$showGrade,$unit_of_measure_speed,$unit_of_measure,$distanceType,v1.3.9";
$cacheFileName = "$gpx,$mtime,$w,$mh,$mt,$gh,$showEle,$showW,$showHr,$showAtemp,$showCad,$donotreducegpx,$pointsoffset,$showSpeed,$showGrade,$unit_of_measure_speed,$unit_of_measure,$distanceType,v1.8.00";
$cacheFileName = md5( $cacheFileName ); $cacheFileName = md5( $cacheFileName );
@ -357,7 +348,7 @@ function wpgpxmaps_handle_shortcodes( $attr, $content = '' ) {
$gpxcache = gpxCacheFolderPath(); $gpxcache = gpxCacheFolderPath();
if ( ! ( $wp_filesystem->exists( $gpxcache ) && $wp_filesystem->is_dir( $gpxcache ) ) ) if ( ! ( file_exists( $gpxcache ) && is_dir( $gpxcache ) ) )
{ {
$wp_filesystem->mkdir( $gpxcache, 0755, true ); $wp_filesystem->mkdir( $gpxcache, 0755, true );
//@mkdir( $gpxcache, 0755, true ); //@mkdir( $gpxcache, 0755, true );
@ -420,10 +411,6 @@ function wpgpxmaps_handle_shortcodes( $attr, $content = '' ) {
$avgv_hr = 0; $avgv_hr = 0;
$avg_temp = 0; $avg_temp = 0;
$tot_len = 0; $tot_len = 0;
echo ( esc_html($e->getMessage()) );
echo ( esc_html("Error getting file $gpxcache from cache") );
} }
} }
@ -655,6 +642,8 @@ function wpgpxmaps_handle_shortcodes( $attr, $content = '' ) {
$ngimgs_data = ''; $ngimgs_data = '';
if ( $ngGalleries != '' || $ngImages != '' ) { if ( $ngGalleries != '' || $ngImages != '' ) {
$ngimgs = getNGGalleryImages( $ngGalleries, $ngImages, $points_x_time, $points_x_lat, $points_x_lon, $dtoffset, $error ); $ngimgs = getNGGalleryImages( $ngGalleries, $ngImages, $points_x_time, $points_x_lat, $points_x_lon, $dtoffset, $error );
$ngimgs_data = '';
foreach ( $ngimgs as $img ) { foreach ( $ngimgs as $img ) {
$data = $img['data']; $data = $img['data'];
$data = str_replace( '\n', '', $data ); $data = str_replace( '\n', '', $data );
@ -721,16 +710,15 @@ function wpgpxmaps_handle_shortcodes( $attr, $content = '' ) {
<div id="wpgpxmaps_' . esc_attr( $r ) . '_osm_footer" class="wpgpxmaps_osm_footer" style="display:none;"><span> &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors</span></div> <div id="wpgpxmaps_' . esc_attr( $r ) . '_osm_footer" class="wpgpxmaps_osm_footer" style="display:none;"><span> &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors</span></div>
</div> </div>
<canvas id="myChart_' . esc_attr( $r ) . '" class="plot" style="width:' . esc_attr( $w ) . '; height:' . esc_attr( $gh ) . '"></canvas> <canvas id="myChart_' . esc_attr( $r ) . '" class="plot" style="width:' . esc_attr( $w ) . '; height:' . esc_attr( $gh ) . '"></canvas>
<div id="ngimages_' . esc_attr( $r ) . '" class="ngimages" style="display:none">' . $ngimgs_data . '</div> <div id="ngimages_' . esc_attr( $r ) . '" class="ngimages" style="display:none">' . wp_kses_post( $ngimgs_data ) . '</div>
<div id="report_' . esc_attr( $r ) . '" class="report"></div> <div id="report_' . esc_attr( $r ) . '" class="report"></div>
</div> </div>
' . esc_html( $error ) . ' ' . esc_html( $error ) . '
<script type="module"> <script type="text/javascript">
import { WPGPXMaps } from "' . plugins_url( 'assets/dist/WP-GPX-Maps.es.js', __FILE__ ) . '";
window.addEventListener("load", function() { jQuery(document).ready(function() {
var wpgpxmaps_' . esc_js( $r ) . ' = new WPGPXMaps({ jQuery( "#wpgpxmaps_' . esc_js( $r ) . '" ).wpgpxmaps( {
targetId : "' . esc_js( $r ) . '", targetId : "' . esc_js( $r ) . '",
mapType : "' . esc_js( $mt ) . '", mapType : "' . esc_js( $mt ) . '",
mapData : [' . esc_js( $points_maps ) . '], mapData : [' . esc_js( $points_maps ) . '],
@ -767,13 +755,6 @@ function wpgpxmaps_handle_shortcodes( $attr, $content = '' ) {
pluginUrl : "' . esc_url( plugins_url() ) . '", pluginUrl : "' . esc_url( plugins_url() ) . '",
TFApiKey : "' . esc_js( get_option( 'wpgpxmaps_openstreetmap_apikey' ) ) . '", TFApiKey : "' . esc_js( get_option( 'wpgpxmaps_openstreetmap_apikey' ) ) . '",
MapBoxApiKey : "' . esc_js( get_option( 'wpgpxmaps_mapbox_apikey' ) ) . '", MapBoxApiKey : "' . esc_js( get_option( 'wpgpxmaps_mapbox_apikey' ) ) . '",
MapBoxMapType : "' . esc_js( get_option( 'wpgpxmaps_mapbox_type' ) ) . '",
MapBoxMapCustomType : "' . esc_js( get_option( 'wpgpxmaps_mapbox_customtype' ) ) . '",
MapBox3dTerrain : "' . esc_js( filter_var(get_option( 'wpgpxmaps_mapbox_3dterrain' ), FILTER_VALIDATE_BOOLEAN) ) . '",
MapBoxFog : "' . esc_js( filter_var(get_option( 'wpgpxmaps_mapbox_fog' ), FILTER_VALIDATE_BOOLEAN) ) . '",
MapBoxAnimateOnLoading : "' . esc_js( get_option( 'wpgpxmaps_mapbox_load_animation' ) ) . '",
langs : { langs : {
altitude : "' . esc_js( __( 'Altitude', 'wp-gpx-maps' ) ) . '", altitude : "' . esc_js( __( 'Altitude', 'wp-gpx-maps' ) ) . '",
currentPosition : "' . esc_js( __( 'Current position', 'wp-gpx-maps' ) ) . '", currentPosition : "' . esc_js( __( 'Current position', 'wp-gpx-maps' ) ) . '",
@ -789,8 +770,8 @@ function wpgpxmaps_handle_shortcodes( $attr, $content = '' ) {
backToCenter : "' . esc_js( __( 'Back to center', 'wp-gpx-maps' ) ) . '" backToCenter : "' . esc_js( __( 'Back to center', 'wp-gpx-maps' ) ) . '"
} }
}); });
}); });
</script>'; </script>';