Quantcast
Channel: Alicia Ramirez
Viewing all articles
Browse latest Browse all 26

Advanced Custom Fields Google Maps Tutorial

$
0
0

One of my go-to plugins is Advanced Custom Fields. It is versatile, and makes adding custom fields to posts, pages, custom post types, and even user profiles a breeze. Unfortunately, their documentation is sometimes not very beginner friendly (I’ve written about this in the past), so today I’ll try to help out those trying to use the Google Map custom field.

Unlike some of their other custom fields, which allow you to simply use <?php the_field('field_name'); ?> to output the content of the field for that particular post or page, this particular field, requires quite a bit of extra code. It’s all listed in their code example; I will simply explain step by step where to put in that code.

Step 1

Paste this code into your stylesheet (style.css), wherever you think is appropriate:

.acf-map {
    width: 100%;
    height: 400px;
    border: #ccc solid 1px;
    margin: 20px 0;
}

 Step 2

Create a new file, and copy-paste the following code in it:

(function($) {

/*
*  render_map
*
*  This function will render a Google Map onto the selected jQuery element
*
*  @type	function
*  @date	8/11/2013
*  @since	4.3.0
*
*  @param	$el (jQuery element)
*  @return	n/a
*/

function render_map( $el ) {

	// var
	var $markers = $el.find('.marker');

	// vars
	var args = {
		zoom		: 16,
		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 );

	});

	// center map
	center_map( map );

}

/*
*  add_marker
*
*  This function will add a marker to the selected Google Map
*
*  @type	function
*  @date	8/11/2013
*  @since	4.3.0
*
*  @param	$marker (jQuery element)
*  @param	map (Google Map object)
*  @return	n/a
*/

function add_marker( $marker, map ) {

	// var
	var latlng = new google.maps.LatLng( $marker.attr('data-lat'), $marker.attr('data-lng') );

	// create marker
	var marker = new google.maps.Marker({
		position	: latlng,
		map			: map
	});

	// add to array
	map.markers.push( marker );

	// 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() {

			infowindow.open( map, marker );

		});
	}

}

/*
*  center_map
*
*  This function will center the map, showing all markers attached to this map
*
*  @type	function
*  @date	8/11/2013
*  @since	4.3.0
*
*  @param	map (Google Map object)
*  @return	n/a
*/

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 );

	});

	// 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
*
*  This function will render each map when the document is ready (page has loaded)
*
*  @type	function
*  @date	8/11/2013
*  @since	5.0.0
*
*  @param	n/a
*  @return	n/a
*/

$(document).ready(function(){

	$('.acf-map').each(function(){

		render_map( $(this) );

	});

});

})(jQuery);

Save that file in your theme folder, and name it google-maps.js or something similar. In my theme, all scripts are in the library/js folder.

Step 3

Now you need to add the scripts to your template. You can paste the link in the header of your template, but that’s not a very good practice; it’s much better to add them via wp_enqueue_script() .

In your functions.php file, add the following code:

function my_theme_add_scripts() {
	wp_enqueue_script( 'google-map', 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false', array(), '3', true );
	wp_enqueue_script( 'google-map-init', get_template_directory_uri() . '/library/js/google-maps.js', array('google-map', 'jquery'), '0.1', true );
}

add_action( 'wp_enqueue_scripts', 'my_theme_add_scripts' );

On line 3, make sure that the path to the script points to where you saved the file in step 2.

Step 3 – optional

If you only want to load your map in certain page, for example, the “Contact” page, you can modify the code above like this:

function my_theme_add_scripts() {
    if (is_page('contact')) {
        wp_enqueue_script( 'google-map', 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false', array(), '3', true );
        wp_enqueue_script( 'google-map-init', get_template_directory_uri() . '/library/js/google-maps.js', array('google-map', 'jquery'), '0.1', true );
    }
}

add_action( 'wp_enqueue_scripts', 'my_theme_add_scripts' );

This way, the scripts won’t be loaded in other pages, where they are not necessary.

Step 4

On the template where you want to add the map, add the following code inside the loop:

<?php 

$location = get_field('location');

if( !empty($location) ):
?>
<div class="acf-map">
	<div class="marker" data-lat="<?php echo $location['lat']; ?>" data-lng="<?php echo $location['lng']; ?>"></div>
</div>
<?php endif; ?>

Make sure that you change the name ‘location‘ in get_field('location'); to match the name of your custom field.

That’s it. Your map should be showing, along with the location selected.


Viewing all articles
Browse latest Browse all 26

Trending Articles