Действия

MediaWiki

Common.js: различия между версиями

Материал из Много троп

Нет описания правки
мНет описания правки
 
Строка 47: Строка 47:


             const blob = new Blob([gpx], {
             const blob = new Blob([gpx], {
                 type: 'application/gpx+xml'
                 type: 'application/gpx+xml;charset=utf-8'
             });
             });


Строка 75: Строка 75:


function geoJsonToGpx(geojson) {
function geoJsonToGpx(geojson) {
     const features = geojson.type === 'FeatureCollection'
     let features = [];
        ? geojson.features
        : [geojson];


     const points = [];
    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) {
     for (const feature of features) {
        const geometry = feature.geometry;
         if (!feature || !feature.geometry) {
 
         if (!geometry) {
             continue;
             continue;
         }
         }
        const geometry = feature.geometry;


         if (geometry.type === 'LineString') {
         if (geometry.type === 'LineString') {
             for (const coordinate of geometry.coordinates) {
             for (const coordinate of geometry.coordinates || []) {
                 points.push(coordinate);
                 const longitude = coordinate[0];
                const latitude = coordinate[1];
 
                if (longitude !== undefined && latitude !== undefined) {
                    trackPoints.push(
                        `      <trkpt lat="${latitude}" lon="${longitude}"></trkpt>`
                    );
                }
             }
             }
         } else if (geometry.type === 'Point') {
         }
            points.push(geometry.coordinates);
 
         } else if (geometry.type === 'MultiLineString') {
         if (geometry.type === 'MultiLineString') {
             for (const line of geometry.coordinates) {
             for (const line of geometry.coordinates || []) {
                 for (const coordinate of line) {
                 for (const coordinate of line) {
                     points.push(coordinate);
                     const longitude = coordinate[0];
                    const latitude = coordinate[1];
 
                    if (longitude !== undefined && latitude !== undefined) {
                        trackPoints.push(
                            `      <trkpt lat="${latitude}" lon="${longitude}"></trkpt>`
                        );
                    }
                 }
                 }
             }
             }
Строка 103: Строка 129:
     }
     }


     const trackPoints = points.map(function (coordinate) {
     if (trackPoints.length === 0) {
        const longitude = coordinate[0];
        throw new Error('В GeoJSON не найдено ни одной координаты LineString');
        const latitude = coordinate[1];
    }
 
        return `      <trkpt lat="${latitude}" lon="${longitude}"></trkpt>`;
    }).join('\n');


     return `<?xml version="1.0" encoding="UTF-8"?>
     return `<?xml version="1.0" encoding="UTF-8"?>
Строка 117: Строка 140:
     <name>Маршрут</name>
     <name>Маршрут</name>
     <trkseg>
     <trkseg>
${trackPoints}
${trackPoints.join('\n')}
     </trkseg>
     </trkseg>
   </trk>
   </trk>
</gpx>`;
</gpx>`;
}
}

Текущая версия от 00:04, 23 сентября 2026

/* Размещённый здесь код 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>`;
}