cliff
9/19/2016 - 10:52 PM

The Events Calendar: Tribe [tribe_venues_map] shortcode

The Events Calendar: Tribe [tribe_venues_map] shortcode

<?php

/**
 * The Events Calendar: [tribe_venues_map] shortcode
 * Preview: https://cl.ly/3Z1e000U3L0U
 * 
 * By Nico and Cliff 2016-08-05
 * From https://gist.github.com/cliffordp/8ecb7022d92f9c989e2e72ecdcf25c60
 */
function tribe_venues_map_logic ( $atts ){
	
	$url = apply_filters( 'tribe_events_google_maps_api', 'https://maps.google.com/maps/api/js' );
	$url = $url . '&callback=tribe_venues_map';

	wp_enqueue_script( 'tribe_events_google_maps_api', $url, array(), false, true );
	wp_enqueue_script( 'jquery' );

	add_action( 'wp_footer', function () {  ?> 
		<style>
			#tribe-venue-map {
				width: 100%;
				height: 400px;
			}
		</style>
		<script>
		function tribe_venues_map() {

			var map = new google.maps.Map( document.getElementById( 'tribe-venue-map' ), {
				center: {lat: 34.5133, lng: -94.1629},
				zoom: 2
			} );

			<?php

			$venues = get_posts( array( 'post_type' => Tribe__Events__Main::VENUE_POST_TYPE, 'posts_per_page' => -1 ) );

			foreach ( $venues as $venue ) {

				$coordinates = tribe_get_coordinates ( $venue->ID );

				if ( $coordinates['lat'] != 0 && $coordinates['lng'] != 0 ) { ?>

					window['marker_' + <?php echo $venue->ID; ?>] = new google.maps.Marker({
						position: {lat: <?php echo $coordinates['lat']; ?>, lng: <?php echo $coordinates['lng']; ?>},
						map: map,
						title: "<?php echo $venue->post_title; ?>"
					});

					window['info_' + <?php echo $venue->ID; ?>] = new google.maps.InfoWindow({
						content: "<?php echo $venue->post_title; ?>"
					});

					window['marker_' + <?php echo $venue->ID; ?>].addListener('click', function() {
						window['info_' + <?php echo $venue->ID; ?>].open(map, window['marker_' + <?php echo $venue->ID; ?>]);
					});

				<?php 
				}
			} ?>
		}
		
		</script>

	<?php });

	return '<div id="tribe-venue-map"></div>';

}
add_shortcode( 'tribe_venues_map', 'tribe_venues_map_logic' );