Support

Home Forums Add-ons User Submitted Multiple Post Points on Google Maps

Solved

Multiple Post Points on Google Maps

  • I’ve looked everywhere for documentation and even google searched a few terms I thought would leave me to some help.

    I want to put multiple coordinates from posts using the google maps addon to display multiple points on a google map and i’m not sure where to start.

    • Elliot

    • November 7, 2013 at 2:30 pm

    Hi @mvmonroe

    This is a good question. One that I will soon cover in a lengthy documentation article on the new google maps field found in ACF 4.3

    For now, you need to break up this task into small and easy to achieve sub tasks like so:

    1. Use the Google API to create a map
    2. Use the Google API to create a marker on the map
    3. Use the Google API to create multiple markers on the map
    4. Loop through the posts you want on the map
    5. For each post, load the co-ordinates data
    6. Use what you learned in step 3 to render the map

    You can get started here:
    https://developers.google.com/maps/documentation/javascript/examples/marker-simple

  • Thank You! I will work through your suggestions and bring back to the support community my code.

    • Elliot

    • November 8, 2013 at 5:01 pm

    Hi @mvmonroe

    Got some great resources for you:
    http://www.advancedcustomfields.com/resources/field-types/google-map/

    Thanks
    E

  • This is my code:

    <style type="text/css">
     .acf-map {
    	width: 960px;
    	height: 400px;
    	border: #ccc solid 1px;
    	margin: 10px 2px 20px;
    }
     </style>
    
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script type="text/javascript">
    (function($) {
     /*
    *  render_map
    *  This function will render a Google Map onto the selected jQuery element
    */
     function render_map( $el ) {
     	// var
    	var $markers = $el.find('.marker');
     	// vars
    	var args = {
    		zoom		: 14,
    		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
    */
    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
    */
     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( 14 );
    	}
    	else
    	{
    		// fit to bounds
    		map.fitBounds( bounds );
    	}
     }
    /*
    *  document ready
    *  This function will render each map when the document is ready (page has loaded)
    */
     $(document).ready(function(){
     	$('.acf-map').each(function(){
     		render_map( $(this) );
     	});
     });
     })(jQuery);
    </script>
    
    			<?php 
    				$mapposts = new WP_Query( array( 
    									'post_status' => 'publish', 
    									'post_type' => 'post_type_name' 
    									) );
    			?>
    			
    		<div class="acf-map">
    
    			<?php while ( $mapposts->have_posts() ) : $mapposts->the_post(); ?>
    			<?php
    					$location = get_field('c_gmaps');
    					$gtemp = explode ('|', $location);
    					$coord = explode (',', $gtemp[1]);
    					$lat = (float) $coord[0];
    					$lng = (float) $coord[1];
    			?>
    
    				<div class="marker" data-lat="<?php echo $lat; ?>" data-lng="<?php echo $lng; ?>">
    					<p class="address"><?php echo $gtemp[0]; ?></p>
    					
    				</div>
    						
    			<?php endwhile; ?>
    			
    		</div><!-- .acf-map -->
     
    			<?php wp_reset_query();  // Restore global post data stomped by the_post(). ?>

    I’m querying a post type to get the map coordinates from each post.

    The only problem I’m having, the markers don’t close when you click on another marker. I’ll search the google support for this.

    Also, I originally had the post type set to ‘any’ and because I still had the default sample post published and was giving a marker of coords 0,0 and centered my map all the way zoomed out. I guess I could add an if get field to the code so that it only displays markers for populated coords or exclude coords of 0,0.

    • mvmonroe

    • November 10, 2013 at 12:10 pm

    Is there a way to change the color of a marker based on a radio button selection on each post?

    • Elliot

    • November 10, 2013 at 3:23 pm

    Hi @mvmonroe

    This kind of customization is not really appropriate for the ACF support forum
    The google maps API contains thousands of examples and so does stack overflow.

    Please consult outside support for customizing the color of the marker.

    I’ll update my docs soon to also close the infoWindow but this should not be hard to find on the net

  • I was referring to the radio button field and how to use it to choose the icon, I have the google dev docs on how to add the markers to the map with the icon base url and icon selection, it’s just making it choose in the loop, which radio button selection it is and then what color or icon to use. Can you use php/acf functions in the javascript code of google?

  • @elliot

    maybe this can help with the close infoWindow

    http://stackoverflow.com/questions/1544739/google-maps-api-v3-how-to-remove-all-markers/1544885#1544885

  • This is more for people searching how to do this, and I don’t mind sharing the code as it helps increase the use of ACF.

    Here is how I modified the Icon used to display the marker or markers on the map with their own custom icon marker.

    First, find the add Marker function in the js:
    function add_marker( $marker, map ) {

    Add this line of code just below it (adjusting the folder path to your icon):

    // var icon
    	var image = '/icon.png';

    Next, we need to add the icon to the create Marker variable, find this code:

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

    Now, make it look like this:

    // create marker
    	var marker = new google.maps.Marker({
    		position	: latlng,
    		map			: map,
    		icon		: image

    Don’t forget the comma behind map if your just adding the line icon : image.

    Now to figure out how to modify the icon.png to display different color icons based on an ACF radio button field.

  • This reply has been marked as private.
    • mvmonroe

    • November 11, 2013 at 12:30 pm

    @elliot

    I added this code right at the end of the // show info window on marker click and it now closes infoWindows on map click

    // close info window when map is clicked
         google.maps.event.addListener(map, 'click', function(event) {
            if (infowindow) {
                infowindow.close(); }
    		}); 

    Havn’t found a solution to close infoWindow on another Marker click.
    Does not close on drag and drop.

    Also, is there a way to hide the content of the infoWindow until the map loads, before the map initializes, the content of all markers are shown and expands past the height of the map.

    • Elliot

    • November 11, 2013 at 4:14 pm

    Hi @mvmonroe

    Feel free to post your code findings here, but this kind of customization is not what the ACF support forum is for. This plugin is for saving / loading PHP data.

    Thanks
    E

    • mvmonroe

    • November 11, 2013 at 10:01 pm

    So someone can’t get support from someone other than you in the support forums? I can’t ask about how to go about working with an acf addon because it uses slightly modified code from the wp mark up so it makes coding things with acf a little bit different and thus new to me. I can’t get simple support or pointed in a direction I need to go because, even though i’ve purchased two of your addons, I can’t get even simple support besides the “this isn’t what the forums are designed for” spill. Not to be rude, but these are simple questions about how to use your modified code, that is all.

    • mvmonroe

    • November 11, 2013 at 10:02 pm

    no need to reply, i’ll handle this my own way.

    • Elliot

    • November 12, 2013 at 4:19 pm

    Hi @mvmonroe

    Really? Is this necessary? I have helped you a lot with your google map questions. Even wrote you an entire code example!

    All I said, is that your questions about marker color customization are not what this ACF support forum is for.

    People like you will never be happy with the free help they receive. And that just confuses me.

    • coreyp

    • November 20, 2013 at 8:54 am

    I look forward to the article, @elliot — will you post a link on this thread when it’s published?

    I’m working on something that would benefit from this very thing.

  • Hello all,

    I noticed that this bit of @mvmonroe ‘s code didn’t work for me.

    <?php
    					$location = get_field('c_gmaps');
    					$gtemp = explode ('|', $location);
    					$coord = explode (',', $gtemp[1]);
    					$lat = (float) $coord[0];
    					$lng = (float) $coord[1];
    			?>
    
    				<div class="marker" data-lat="<?php echo $lat; ?>" data-lng="<?php echo $lng; ?>">

    No longtitude/latitude parameteres were being passed to the markers. I fixed it by changing it to this:

    <?php
    				$location = get_field('c_gmaps');
    				$gtemp = explode (',',  implode($location));
    				$coord = explode (',', implode($gtemp));
    ?>
    
    				<div class="marker" data-lat="<?php echo $location[lat]; ?>" data-lng="<?php echo $location[lng]; ?>">
    					<p class="address"><?php  echo $gtemp[0]; ?><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>		
    				</div>

    Hope this helps someone.

  • I saw a few other people struggling with getting infowindows to close when a new one opens. I managed to find a solution that works for me, but I’m no JS / GmapsAPI expert – so if there’s a better way, I’m all ears. Just thought I’d share what I came up with.

    Turns out it was just a matter of defining the infowindow variable outside of the each() – so that only one infowindow is created, then what we do is swap the infowindow content on the click listener, which closes the previous infowindow and prevents that chaotic cluster of opened infowindows we all hate. I also added another listener so when the user clicks the map, the infowindow closes.

    I’ve commented the code as well in case anyone wants to see the changes to the default code supplied in the ACF documentation.

    <script type="text/javascript">
    (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 );
    	
    	
    }
    
    // create info window outside of each - then tell that singular infowindow to swap content based on click
    var infowindow = new google.maps.InfoWindow({
    content		: '' 
    });
    
    /*
    *  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() )
    {
    	
    	
    	
    
    	// show info window when marker is clicked & close other markers
    	google.maps.event.addListener(marker, 'click', function() {
    		//swap content of that singular infowindow
    				infowindow.setContent($marker.html());
    		        infowindow.open(map, marker);
    	});
    	
    	// close info window when map is clicked
    	     google.maps.event.addListener(map, 'click', function(event) {
    	        if (infowindow) {
    	            infowindow.close(); }
    			}); 
    			
    		
    }
    
    }
    
    /*
    *  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);
    </script>
  • Many, many, many thanks @mvmonroe and @Anthi Malteza, you gave me a huge help.

  • @mvmonroe did you ever figure out how to open one infowindow at a time? I’m currently struggling with that

  • The snippet I shared above does what you’re after. Try it out!

  • @cmdbase

    The code above shows an error that infowindow is not defined and only closes the infowindows when you clip on the map?

  • Check to make sure

    
    var infowindow = new google.maps.InfoWindow({
    content		: '' 
    });
    

    is defined after

    
    center_map( map ); }
    

    This sets the infowindow to be a global variable that should prevent that error from showing up.

  • @cmdbase

    my fault entirely. I had it defined in the render map variable. Works like a charm! Also greatly appreciate your follow up

Viewing 25 posts - 1 through 25 (of 37 total)

You must be logged in to reply to this topic.