Gists

1 month ago
<?php 

/**
 * prevent default map loading 
 **/
add_filter( 'facetwp_load_gmaps', '__return_false' ); 

/**
 * load gmaps script for cmplz
 */
add_filter( 'cmplz_added_scripts', function( $added_scripts ) {
    $params = [
        'key'   => FWP()->display->get_gmaps_api_key(),
        'v'     => 'quarterly',
    ];
    $params_string = '';
    foreach ( apply_filters( 'facetwp_gmaps_params', $params ) AS $param => $val ) {
        $params_string .=  $param . ': "' . $val . '",';
    }

    $script = '(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. FacetWP\'s instance is ignored."):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({';
    $script .= $params_string;
    $script .= '});';

    $added_scripts[] = [
        'name' => 'FacetWP',
        'category' => 'marketing',
        'editor' => $script,
        'async' => 0
    ];

    return $added_scripts;

});

/**
 * Init map after cookies accepted
 *
 */

add_action('wp_enqueue_scripts', function()
{
    ob_start();
?>
    <script>
        /**
         * Make functions await for 'ms' milliseconds
         * https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep
         *
         */
        function sleep(ms) {
            return new Promise(resolve => setTimeout(resolve, ms));
        }

        /**
         * Wait for 'facetwp-map' to be initialized
         *
         */
        const checkIfMapIsInitialized = () => {
            const map = document.getElementById('facetwp-map');
            return map.children.length > 0 && FWP_MAP.markersArray.length > 0;
        }

        /**
         * Wait for 'FWP', 'FWP_MAP' and 'FWP_MAP.map' to be set
         *
         */
        const checkIfFWPExists = async () => {
            if (typeof FWP !== 'undefined' && typeof FWP_MAP !== 'undefined' && typeof FWP_MAP.map !== 'undefined') {
                return true;
            }
            await sleep(500);
            checkIfFWPExists();
        }

        /**
         * Reinitialize FacetWP Google Maps' map
         *
         */
        const reinitializeMap = async () => {
            FWP.loaded = false;
            delete FWP.frozen_facets.map; // change 'map' to name of your map
            FWP.refresh();
            await sleep(6000);
            if (checkIfMapIsInitialized() !== true) {
                reinitializeMap();
            }
        }

        const fixMap = async (event) => {
            if (!cmplz_has_consent("marketing")) {
                return;
            }
            if (event.type === "cmplz_enable_category") {
                document.removeEventListener('cmplz_enable_category', fixMap);
                window.removeEventListener('load', fixMap);
            }
            await checkIfFWPExists();

            if (checkIfMapIsInitialized() !== true) {
                await reinitializeMap();
            }
        }

        document.addEventListener('cmplz_enable_category', fixMap);
        window.addEventListener('load', fixMap);
    </script>
<?php
    $script = ob_get_clean();
    $script = str_replace(array('<script>', '</script>'), '', $script);
    wp_add_inline_script('cmplz-cookiebanner', $script);

}, PHP_INT_MAX);
2 months ago
<?
/**
 * disables map filtering if enabled when other
 * filters are used instead
 **/
add_action( 'facetwp_scripts', function() {
 ?>
  <script>
    (function($) {
    document.addEventListener('facetwp-refresh', function() {
        if ( null !== FWP.active_facet &&
                '' !== $(FWP.active_facet.nodes[0]).attr('data-name' ) &&
                /** change 'my_map_facet' to name of your map facet */
                'my_map_facet' !== $(FWP.active_facet.nodes[0]).attr( 'data-name' ) ) {
            var $button = $('.facetwp-map-filtering');
            $button.text(FWP_JSON['map']['filterText']);
            FWP_MAP.is_filtering = false;
            $button.toggleClass('enabled');
            FWP.facets.map = [];
        } 
    });
    })(fUtil);
  </script>
  <?php
}, 100 );
4 months ago
<?php
// For a Proximity facet, index an ACF Google Maps field of a post linked by an ACF Post Object field.
// The Proximity facet's data source can be set to anything as long as that value is not empty. E.g. 'Post Type'.
// The 'Return Format' of the Post Object field does not matter: it works with both 'Post Object' and 'Post ID'.
// See: https://facetwp.com/help-center/developers/hooks/indexing-hooks/facetwp_index_row/#index-values-in-a-related-custom-field

add_filter( 'facetwp_index_row', function( $params, $class ) {

  if ( 'my_proximity_facet' == $params['facet_name'] ) { // Change "my_proximity_facet" to the name of your Proximity facet

    $post_id = $params['post_id'];
      
    // Get the Post Object field value 
    $location_id = get_field( 'my_acf_post_object field', $post_id ); // Change "my_acf_post_object field" to the name of your ACF Post Object field

    $location = '';
    if ( $location_id ) { // Check if the Post Object field has a value
      // If we have a Post Object field value, use it to get the Google Maps field value  
      $location = get_field( 'my_acf_googlemapfield', $location_id ); // Change "my_acf_googlemapfield" to the name of your ACF Google Maps field
    }

    // If there is a location, index it, otherwise skip this post by setting facet_value to ''.  
    $params['facet_value'] = empty( $location ) ? '' : $location['lat'];
    $params['facet_display_value'] = empty( $location ) ? '' : $location['lng'];
      
    // Optionally replicate the extra checks that Proximity facets normally have:

    // 1. Make sure lat and lng are valid floats
    $params['facet_value'] = $params['facet_value'] == (float)$params['facet_value'] ? (float)$params['facet_value'] : '';
    $params['facet_display_value'] = $params['facet_display_value'] == (float)$params['facet_display_value'] ? (float)$params['facet_display_value'] : '';

    // 2. Check for a valid range of lat and lng
    if  ( '' == $params['facet_value'] || '' == $params['facet_display_value'] || 90 < abs( $params['facet_value'] ) || 180 < abs( $params['facet_display_value'] ) ) {
      $params['facet_value'] = ''; // don't index
    }
      
  }

  return $params;
}, 10, 2 );
2 years ago
<?php
/**
 ** Facet automatically indexes latitude and longitude from an ACF map field
 ** This will index other data saved in other sub fields
 ** Note that these fields are optional and may not exist
 ** See ACF docs for more - https://www.advancedcustomfields.com/resources/google-map/#template-usage
 **/

add_filter( 'facetwp_index_row', function( $params, $class ) {
	if ( 'my_facet' == $params['facet_name'] ) { // change my_facet to name of your facet
		$post_id = $params['post_id'];
		$acf = str_replace( 'acf/', '', $params['facet_source'] );
		$location = get_field( $acf, $post_id );
		$value = $location['city'] ?? ''; 
		if ( '' != $value ) {
			$params['facet_value'] = $value;
			$params['facet_display_value'] = $value;
		} else {
			$params['facet_value'] = ''; // don't index
		}
	}
	return $params;
}, 10, 2 );
2 years ago
<?php
add_action('facetwp_scripts', function () {
  ?>
  <script>
    (function($) {
      document.addEventListener('facetwp-refresh', function() {
        if ( 'undefined' != typeof FWP_MAP && true === FWP_MAP.is_filtering) {
          $('.facetwp-location').val(''); // reset the value of the input field
          $('.facetwp-lat').val(''); // reset hidden field
          $('.facetwp-lng').val(''); // reset hidden field
          $('.facetwp-radius option').each(function () {
            if (this.defaultSelected) {
              this.selected = true;
              return false;
            } // reset default radius if it is a dropdown
          });
          FWP.facets['my_proximity_facet'] = []; // change 'my_proximity_facet' to name of your Proximity facet
        }
      });
    })(fUtil);
  </script>
  <?php
}, 100);
2 years ago
<?php
/** turn off map filtering when resetting the map facet **/
add_action('facetwp_scripts', function () {
?>
    <script>        
        (function($) {
            FWP.hooks.addAction('facetwp/reset', function() {
                $.each(FWP.facet_type, function(type, name) {
                    if ('map' === type) {
                        var $button = $('.facetwp-map-filtering');
                        $button.text(FWP_JSON['map']['filterText']);
                        FWP_MAP.is_filtering = false;
                        $button.toggleClass('enabled');
                    }
                });
            });
        })(fUtil);	
    </script>
<?php
}, 100);
4 months ago
<style>
.gm-style-iw-c,
.gm-style-iw-tc {
  display: none;
}
</style>
2 years ago
<?php
add_filter( 'facetwp_render_output', function( $output, $params ) {
    if ( FWP()->ajax->is_preload && isset( $output['settings']['map']['locations'] ) ) {
        $output['settings']['map']['locations'] = [];
    }
    return $output;
}, 11, 2 );
2 years ago
<?php
/** 
 ** Adds marker click action to add a circle radius around clicked marker
 ** Clicking another marker clears the previous circle
 ** Note: facetwp_scripts action requires FacetWP v4.2.2+
 ** More info: https://facetwp.com/help-center/facets/facet-types/map/advanced-map-customizations/#display-a-circle-or-other-shape-around-clicked-markers
 **/

add_action( 'facetwp_scripts', function() {
    ?>
      <script>
        (function($) {
          FWP.hooks.addAction('facetwp_map/marker/click', function(marker) {

            // Clear existing marker if it exists
            if ( 'undefined' !== typeof FWP_MAP.circ )
              FWP_MAP.circle.setMap(null); // Clear circle from map
              FWP_MAP.circle = null; // Remove circle instance entirely

            // var post_id = marker.post_id; // The marker's post_id could be used to apply this code only to certain markers.
            var lat = marker.position.lat();
            var lng = marker.position.lng();

            FWP_MAP.circ = new google.maps.Circle({
                center: {
                    lat: lat,
                    lng: lng
                },
                radius: 25000, // Circle radius in meters
                fillColor: '#FF0000', // Circle coloring
                fillOpacity: 0.35, // Circle opacity
                strokeColor: "#FF0000", // Circle outline color
                strokeOpacity: 0.8, // Circle outline opacity
                strokeWeight: 2, // Circle outline thickness
                map: FWP_MAP.map
            });
            
            // Optional: when an infoWindow is closed, clear the circle from the map
            google.maps.event.addListener(FWP_MAP.infoWindow, 'closeclick', function() {
              FWP_MAP.circle.setMap(null);
            });

            // Optional: when the map is clicked anywhere, clear the circle from map
            google.maps.event.addListener(FWP_MAP.map, 'click', function(event) {
             FWP_MAP.circle.setMap(null);
            });

          });
        })(fUtil);
      </script>
    <?php
  }, 100 );
3 years ago
<?php
/** basic check to keep only one map marker per location
 ** assumes lat is unique without having to check lng also
 **/

Class FWPMapDulicateChecker
{
    public $locations = [];

    function __construct() {

        add_filter( 'facetwp_map_marker_args', function( $args, $post_id ) {
            $lat = $args['position']['lat'];
            if ( false === array_search( $lat, $this->locations ) ) {
                $this->locations[] = $lat;
            } else {
                return false;
            }
            return $args;
        }, 10, 2 );
    }
}
new FWPMapDulicateChecker();