MediaWiki:Common.js
Материал из Много троп
Замечание: Возможно, после публикации вам придётся очистить кэш своего браузера, чтобы увидеть изменения.
- Firefox / Safari: Удерживая клавишу Shift, нажмите на панели инструментов Обновить либо нажмите Ctrl+F5 или Ctrl+R (⌘+R на Mac)
- Google Chrome: Нажмите Ctrl+Shift+R (⌘+Shift+R на Mac)
- Edge: Удерживая Ctrl, нажмите Обновить либо нажмите Ctrl+F5
- Opera: Нажмите Ctrl+F5.
/* Размещённый здесь код JavaScript будет загружаться пользователям при обращении к каждой странице */
$(function () {
$('.hidden-iframe-container').each(function () {
const container = this;
const iframe = container.querySelector('.hidden-iframe');
if (!iframe) {
return;
}
let loaded = false;
// Считаем iframe загруженным после события load
iframe.addEventListener('load', function () {
loaded = true;
// Небольшая задержка перед отображением
setTimeout(function () {
container.style.display = '';
}, 3000); // 3000 мс = 3 секунды
});
// Если iframe не загрузился за 5 секунд, оставляем его скрытым
setTimeout(function () {
if (!loaded) {
container.remove();
// Или вместо удаления:
// container.style.display = 'none';
}
}, 5000);
});
});
mw.hook('wikipage.content').add(function ($content) {
const button = document.getElementById('download-gpx');
const dataElement = document.getElementById('route-data');
if (!button || !dataElement) {
return;
}
function downloadGpx() {
try {
const data = JSON.parse(dataElement.textContent.trim());
const gpx = geoJsonToGpx(data);
const blob = new Blob([gpx], {
type: 'application/gpx+xml;charset=utf-8'
});
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'route.gpx';
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
} catch (error) {
console.error('Не удалось создать GPX-файл:', error);
}
}
button.addEventListener('click', downloadGpx);
button.addEventListener('keydown', function (event) {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
downloadGpx();
}
});
});
function geoJsonToGpx(geojson) {
let features = [];
if (geojson.type === 'FeatureCollection') {
features = geojson.features || [];
} else if (geojson.type === 'Feature') {
features = [geojson];
} else if (geojson.type === 'LineString') {
features = [{
geometry: geojson
}];
} else if (geojson.type === 'MultiLineString') {
features = [{
geometry: geojson
}];
}
const trackPoints = [];
for (const feature of features) {
if (!feature || !feature.geometry) {
continue;
}
const geometry = feature.geometry;
if (geometry.type === 'LineString') {
for (const coordinate of geometry.coordinates || []) {
const longitude = coordinate[0];
const latitude = coordinate[1];
if (longitude !== undefined && latitude !== undefined) {
trackPoints.push(
` <trkpt lat="${latitude}" lon="${longitude}"></trkpt>`
);
}
}
}
if (geometry.type === 'MultiLineString') {
for (const line of geometry.coordinates || []) {
for (const coordinate of line) {
const longitude = coordinate[0];
const latitude = coordinate[1];
if (longitude !== undefined && latitude !== undefined) {
trackPoints.push(
` <trkpt lat="${latitude}" lon="${longitude}"></trkpt>`
);
}
}
}
}
}
if (trackPoints.length === 0) {
throw new Error('В GeoJSON не найдено ни одной координаты LineString');
}
return `<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1"
creator="MediaWiki"
xmlns="http://www.topografix.com/GPX/1/1">
<trk>
<name>Маршрут</name>
<trkseg>
${trackPoints.join('\n')}
</trkseg>
</trk>
</gpx>`;
}