?AlkantarClanX12

Your IP : 216.73.217.134


Current Path : /home/r/a/n/rankinh/saintgilleslesbains-bis/wp-content/plugins/sglb-map/
Upload File :
Current File : /home/r/a/n/rankinh/saintgilleslesbains-bis/wp-content/plugins/sglb-map/sglb-map.php

<?php
/**
 * Plugin Name: SGLB – Carte Interactive Leaflet
 * Description: Affiche une carte Leaflet avec les établissements de l'annuaire (sglb_listing). Shortcode : [sglb_map]
 * Version:     1.0.0
 * Author:      AIA
 */

if ( ! defined( 'ABSPATH' ) ) exit;

// ─────────────────────────────────────────
// 1. ENQUEUE LEAFLET (seulement si le shortcode est présent)
// ─────────────────────────────────────────
add_action( 'wp_enqueue_scripts', 'sglb_map_enqueue' );
function sglb_map_enqueue() {
    wp_register_style(
        'leaflet',
        'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css',
        [],
        '1.9.4'
    );
    wp_register_script(
        'leaflet',
        'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js',
        [],
        '1.9.4',
        true
    );
}

// ─────────────────────────────────────────
// 2. SHORTCODE [sglb_map]
//
// Paramètres optionnels :
//   height   – hauteur de la carte          (défaut : 520px)
//   zoom     – niveau de zoom initial       (défaut : 12)
//   taxonomy – slug de la taxonomie catég.  (défaut : sglb_listing_cat)
//              ⚠️ Adaptez ce slug au nom réel de votre taxonomie.
//
// Exemple : [sglb_map height="600px" zoom="11" taxonomy="sglb_listing_cat"]
// ─────────────────────────────────────────
add_shortcode( 'sglb_map', 'sglb_map_shortcode' );
function sglb_map_shortcode( $atts ) {

    $atts = shortcode_atts( [
        'height'   => '520px',
        'zoom'     => '12',
        'taxonomy' => 'sglb_listing_cat', // ← adaptez si nécessaire
    ], $atts, 'sglb_map' );

    // Charger Leaflet sur cette page
    wp_enqueue_style( 'leaflet' );
    wp_enqueue_script( 'leaflet' );

    // ── Récupérer tous les listings publiés ayant des coords GPS
    $listings = get_posts( [
        'post_type'      => 'sglb_listing',
        'post_status'    => 'publish',
        'posts_per_page' => -1,
        'meta_query'     => [ [
            'key'     => 'sglb_gps',
            'value'   => '',
            'compare' => '!=',
        ] ],
    ] );

    $markers   = [];
    $sum_lat   = 0;
    $sum_lng   = 0;
    $valid     = 0;

    foreach ( $listings as $post ) {
        $gps = get_post_meta( $post->ID, 'sglb_gps', true );
        if ( ! $gps ) continue;

        // Format attendu : "-21.0452, 55.2234"
        $parts = array_map( 'trim', explode( ',', $gps ) );
        if ( count( $parts ) < 2 ) continue;

        $lat = (float) $parts[0];
        $lng = (float) $parts[1];
        if ( $lat === 0.0 && $lng === 0.0 ) continue; // coordonnées vides

        // Catégorie (première terme de la taxonomie)
        $terms = get_the_terms( $post->ID, sanitize_key( $atts['taxonomy'] ) );
        $cat   = ( $terms && ! is_wp_error( $terms ) ) ? $terms[0]->name : '';

        $markers[] = [
            'lat'  => $lat,
            'lng'  => $lng,
            'name' => $post->post_title,
            'cat'  => $cat,
            'url'  => get_permalink( $post->ID ),
        ];

        $sum_lat += $lat;
        $sum_lng += $lng;
        $valid++;
    }

    // Centre : centroïde des markers, ou La Réunion par défaut
    $center_lat = $valid ? round( $sum_lat / $valid, 6 ) : -21.1151;
    $center_lng = $valid ? round( $sum_lng / $valid, 6 ) : 55.5364;

    $map_id  = 'sglb-map-' . uniqid();
    $height  = esc_attr( $atts['height'] );
    $zoom    = intval( $atts['zoom'] );
    $data    = wp_json_encode( $markers );

    ob_start();
    ?>
    <style>
        #<?php echo $map_id; ?> {
            width: 100%;
            height: <?php echo $height; ?>;
            border-radius: 10px;
            box-shadow: 0 2px 12px rgba(0,0,0,.12);
            z-index: 1;
        }

        /* Popup */
        .sglb-popup {
            font-family: inherit;
            min-width: 180px;
            line-height: 1.4;
        }
        .sglb-popup-cat {
            font-size: 11px;
            font-weight: 600;
            color: #0073aa;
            text-transform: uppercase;
            letter-spacing: .6px;
            margin-bottom: 4px;
        }
        .sglb-popup-name {
            font-size: 15px;
            font-weight: 700;
            color: #1a1a1a;
            margin: 0 0 10px;
        }
        .sglb-popup-link {
            display: inline-block;
            background: #0073aa;
            color: #fff !important;
            padding: 6px 14px;
            border-radius: 5px;
            text-decoration: none !important;
            font-size: 12px;
            font-weight: 600;
            transition: background .2s;
        }
        .sglb-popup-link:hover {
            background: #005d8c;
        }
    </style>

    <div id="<?php echo $map_id; ?>"></div>

    <script>
    (function() {
        function initSglbMap() {
            if ( typeof L === 'undefined' ) {
                // Leaflet pas encore chargé, on réessaie
                setTimeout( initSglbMap, 100 );
                return;
            }

            var map = L.map( '<?php echo $map_id; ?>' ).setView(
                [ <?php echo $center_lat; ?>, <?php echo $center_lng; ?> ],
                <?php echo $zoom; ?>
            );

            L.tileLayer( 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution : '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
                maxZoom     : 19
            } ).addTo( map );

            var markers = <?php echo $data; ?>;

            markers.forEach( function( m ) {
                var popup =
                    '<div class="sglb-popup">' +
                    ( m.cat ? '<div class="sglb-popup-cat">' + m.cat + '</div>' : '' ) +
                    '<p class="sglb-popup-name">' + m.name + '</p>' +
                    '<a class="sglb-popup-link" href="' + m.url + '">Voir la fiche →</a>' +
                    '</div>';

                L.marker( [ m.lat, m.lng ] )
                 .addTo( map )
                 .bindPopup( popup, { maxWidth: 260 } );
            } );
        }

        // Lancer après le DOM
        if ( document.readyState === 'loading' ) {
            document.addEventListener( 'DOMContentLoaded', initSglbMap );
        } else {
            initSglbMap();
        }
    })();
    </script>
    <?php
    return ob_get_clean();
}