Wordpress ACF и Google Map фильтр по категориям... и масштабирование

Я строю карту с Google Map и ACF на WordPress сайте. Моя цель - создать фильтруемую карту по категориям: посты - это города, они сгруппированы по категориям, а категории - по странам. Я создал список переключателей для каждой категории, и когда я щелкаю по нему, я отображаю только одну категорию за раз.

Дело в том, что когда я нажимаю переключатель и когда отображаются маркеры страны, я хотел бы увеличить страну. Карта остается на том же уровне масштабирования. Я знаю, что в Интернете есть много подобных примеров, но ни один из них не заставляет карту увеличиваться при нажатии радиокнопки. Есть кто-то, кто мог бы сказать мне, если это возможно таким образом? Я также пробовал с кластером, в этом случае зум работает, но задача состоит в том, чтобы заставить его работать с фильтром (радио-кнопка или флажок или выберите..) заранее спасибо всем, кто может мне помочь!!:)

вот код google.js

(function($) {

// New Map   
// This function will render a Google Map onto the selected jQuery element
function new_map( $el ) {
    // var
    var $markers = $el.find('.marker');
    // vars
    var args = {
        zoom        : 4,
        center      : new google.maps.LatLng(0, 0),
        mapTypeId   : google.maps.MapTypeId.ROADMAP,

    };
    // create map               
    var map = new google.maps.Map( $el[0], args);

    // add a markers reference
    map.markers = [];
    // add markers

    // Filter Markers
    $('.virtual-map-filter').on('change', 'input[type="radio"]', function() {
        filter = $(this);
        filterValue = filter.val();
        if(filter.is(':checked')) {
            map.markers.forEach(function(element) {
                if(element.category == filterValue) {
                    element.setVisible(true); 


                }else{
                    element.setVisible(false);
                }
            });
            } 
            else 
            {
            map.markers.forEach(function(element) {
                if(element.category != filterValue) {
                    element.setVisible(false);
                }
            });
        }
    });
    $markers.each(function(){
        add_marker( $(this), map );
    }); 

    // center map
    center_map( map );
    // return
    return map;
}

// Add Marker 
function add_marker( $marker, map ) {
    // var
    var latlng = new google.maps.LatLng( $marker.attr('data-lat'), $marker.attr('data-lng') );
    var category = $marker.data('category'); // Get category name from data
    // create marker
    var marker = new google.maps.Marker({
        position    : latlng,
        draggable   : true, // set marker to draggable to hide duplicates
        crossOnDrag : false, // hide cross icon on drag event
        map         : map,
        category    : category, // store category as property of marker


    });
    // add to array
    map.markers.push( marker );
    //first hide all the markers
    marker.setVisible(false);

    // if marker contains HTML, add it to an infoWindow
    if( $marker.html() ) {
        // create info window
        var infowindow = new google.maps.InfoWindow({
            content     : $marker.html()
        });

        // show info window when marker is clicked
            google.maps.event.addListener(marker, 'click', function() {
            if (typeof( window.infoopened ) != 'undefined') infoopened.close();
              infowindow.open(map,marker);
              infoopened = infowindow;

    });
    }
}
// Center Map   
function center_map( map ) {
    // vars
    var bounds = new google.maps.LatLngBounds();
    // loop through all markers and create bounds
    $.each( map.markers, function( i, marker ){
        var latlng = new google.maps.LatLng( marker.position.lat(), marker.position.lng() );
        bounds.extend( latlng );
        map.fitBounds(bounds);

    });
    // only 1 marker?
    if( map.markers.length == 1 ) {
        // set center of map
        map.setCenter( bounds.getCenter() );
        map.setZoom( 16 );
    } else {
        // fit to bounds
        map.fitBounds( bounds );

    }


  }
    // Document Ready  
    // global var
    var map = null;
    $(document).ready(function(){
        $('.acf-map').each(function(){
            // create map
            map = new_map( $(this) );
        });
    });

})(jQuery);

и вот часть HTML / PHP

<div class="map-container">
        <?php
        $terms = get_field('category_select');
        if( $terms ): ?>
        <?php foreach( $terms as $term ): 
        $args = array(
            'post_type' => 'post', 
            'category__in' => $term
            );
        $the_query = new WP_Query($args); 
;?><div class="acf-map"><?php
        while ( $the_query->have_posts() ) : $the_query->the_post();
        $location = get_field('google_maps');?>

        <?php
        if( !empty($location) ) { 
            ?>
            <div class="marker" data-category="<?php echo $term->slug ;?>" data-lat="<?php echo $location['lat']; ?>" data-lng="<?php echo $location['lng']; ?>">
                <?php the_post_thumbnail('thumbnail'); ?>
                <h4><a href="<?php the_permalink(); ?>" rel="bookmark"> <?php the_title(); ?></a></h4>
                <p class="address"><?php echo $location['address']; ?></p>
            </div>
            <?php
        }
        endwhile; 
        wp_reset_postdata();
        endforeach ;?>  
        <?php endif; ?>
    </div>
</div>

1 ответ

Решение

Спасибо! наконец-то мне удалось это сделать, но код может быть не лучшим.. я сохранил php-файл таким же, но изменил js-файл следующим образом: -в функции new_map я добавил новый google.maps.LatLngBounds()'и если маркеры видны, я расширил границы с помощью: 'bounds.extend($markers.getPosition())'. Сначала все мои маркеры скрыты с помощью метода marker.setVisible(false) в функции add_marker. Когда я нажимаю переключатель, масштаб карты увеличивается до выбранной страны!! Дело в том, что я не знаю, является ли это лучшим способом сделать это... если у вас есть предложения!! Спасибо

(function($) {

// New Map   
// This function will render a Google Map onto the selected jQuery element
function new_map( $el ) {
    // var
    var $markers = $el.find('.marker');
    // vars
    var args = {
        zoom        : 4,
        center      : new google.maps.LatLng(0, 0),
        mapTypeId   : google.maps.MapTypeId.ROADMAP,

    };
    // create map               
    var map = new google.maps.Map( $el[0], args);

    // add a markers reference
    map.markers = [];
    // add markers
      $markers.each(function(){
        add_marker( $(this), map );
    }); 
    // Filter Markers
    $('.virtual-map-filter').on('change', 'input[type="radio"]', function() 
{
        filter = $(this);
        filterValue = filter.val();
        if(filter.is(':checked')) {
            var bounds = new google.maps.LatLngBounds();
            map.markers.forEach(function( $markers) {
                if( $markers.category == filterValue) {
                     $markers.setVisible(true); 

                    bounds.extend(  $markers.getPosition() );


                }else{
                     $markers.setVisible(false);
                }
            });
               map.fitBounds(bounds);
            } 

    });



    // center map
    center_map( map );
    // return
    return map;
}

    // Add Marker 
    function add_marker( $marker, map ) {
    // var
    var latlng = new google.maps.LatLng( $marker.attr('data-lat'), 
    $marker.attr('data-lng') );
    var category = $marker.data('category'); // Get category name from data
    // create marker
    var marker = new google.maps.Marker({
        position    : latlng,
        draggable   : true, // set marker to draggable to hide duplicates
        crossOnDrag : false, // hide cross icon on drag event
        map         : map,
        category    : category, // store category as property of marker


    });
    // add to array
    map.markers.push( marker );
    //first hide all the markers
    marker.setVisible(false);

    // if marker contains HTML, add it to an infoWindow
    if( $marker.html() ) {
        // create info window
        var infowindow = new google.maps.InfoWindow({
            content     : $marker.html()
        });

        // show info window when marker is clicked
            google.maps.event.addListener(marker, 'click', function() {
            if (typeof( window.infoopened ) != 'undefined') 
            infoopened.close();
              infowindow.open(map,marker);
              infoopened = infowindow;

    });
    }
}
// Center Map   
function center_map( map ) {
    // vars
    var bounds = new google.maps.LatLngBounds();
    // loop through all markers and create bounds
    $.each( map.markers, function( i, marker ){
        var latlng = new google.maps.LatLng( marker.position.lat(), 
        marker.position.lng() );
        bounds.extend( latlng );
        map.fitBounds(bounds);

    });
    // only 1 marker?
    if( map.markers.length == 1 ) {
        // set center of map
        map.setCenter( bounds.getCenter() );
        map.setZoom( 16 );
    } else {
        // fit to bounds
        map.fitBounds( bounds );

    }                                  
  }
    // Document Ready  
    // global var
    var map = null;
    $(document).ready(function(){
        $('.acf-map').each(function(){
            // create map
            map = new_map( $(this) );
        });
    });

 })(jQuery);
Другие вопросы по тегам