WordPress.org

Forums

[Plugin Advanced Custom Fields] Display Google map on your theme (31 posts)

  1. LeRedac
    Member
    Posted 1 year ago #

    Hi there,

    maybe this code is help you for display a Google map from field google map in Advanced Custom Fields plugin.

    Peut être ce bout de code pourra vous être utile pour afficher dans votre thème, la carte google généré via le champs "Google map" du plugin Advanced Custom Fields

    Working whith WordPress 3.8.1

    <div id="view1">
    <?php
    $location = get_field('carte_google');
    if( ! empty($location) ):
    ?>
    <div id="map" style="width: 100%; height: 350px;"></div>
    <script src='http://maps.googleapis.com/maps/api/js?sensor=false' type='text/javascript'></script>
    
    <script type="text/javascript">
      //<![CDATA[
    	function load() {
    	var lat = <?php echo $location['lat']; ?>;
    	var lng = <?php echo $location['lng']; ?>;
    // coordinates to latLng
    	var latlng = new google.maps.LatLng(lat, lng);
    // map Options
    	var myOptions = {
    	zoom: 9,
    	center: latlng,
    	mapTypeId: google.maps.MapTypeId.ROADMAP
       };
    //draw a map
    	var map = new google.maps.Map(document.getElementById("map"), myOptions);
    	var marker = new google.maps.Marker({
    	position: map.getCenter(),
    	map: map
       });
    }
    // call the function
       load();
    //]]>
    </script>
    <?php endif; ?> 
    
    </div>
  2. joshuaiz
    Member
    Posted 1 year ago #

    This really helped - much clearer than the ACF docs.

  3. orangesandlime
    Member
    Posted 1 year ago #

    Thank you SO SO much for sharing this!

  4. lakmar
    Member
    Posted 1 year ago #

    Dear LeRedac

    THANK YOU so much for the help. I am setting up an easy backend to add events via post(Event Category) and with 2 ACF fields.. Event endDate and Map..

    As long as event enddate is less than today's date, i display the event.

    Wanted the map to be displayed on home page as well, and struggled. In my test code, i got an output of "array" for the map field.. Went to ACF site and got completely lost.

    Your code above allowed me to display a map! I am SO excited..

    Merci Beaucoup!

  5. joshmaxrubinstein
    Member
    Posted 1 year ago #

    Thank you. ACF Docs could use this!

  6. jamesfirass
    Member
    Posted 1 year ago #

    Dear LeRedac,
    I am a PHP developer, somewhat new to WP. I tried your code, spiced it up with an if statement to see why it won't show the map. The field name is: "laama_map".
    I don't know where i have got it wrong, but it always executes the else part of the if statement. Thanks for your help in advance!

    Here is my code:

    get_header();
    $postReceivedID='36';
    $foundPost=get_post($postReceivedID);
    global  $foundPost;
    echo  $foundPost->post_title;
    echo   $foundPost->post_content;
    echo   $foundPost->the_date;
    /* $location = get_field('laama_map'); */
    ?>
    <div id="view1" style="background-color:red; height:600px; width:700px; margin-left:300px;">
    <?php
    $location = get_field('laama_map');
    if( ! empty($location) ){
    ?>
    <div id="map" style="width: 100%; height: 350px;"></div>
    <script src='http://maps.googleapis.com/maps/api/js?sensor=false' type='text/javascript'></script>
    
    <script type="text/javascript">
      //<![CDATA[
    	function load() {
    	var lat = <?php echo $location['lat']; ?>;
    	var lng = <?php echo $location['lng']; ?>;
    // coordinates to latLng
    	var latlng = new google.maps.LatLng(lat, lng);
    // map Options
    	var myOptions = {
    	zoom: 9,
    	center: latlng,
    	mapTypeId: google.maps.MapTypeId.ROADMAP
       };
    //draw a map
    	var map = new google.maps.Map(document.getElementById("map"), myOptions);
    	var marker = new google.maps.Marker({
    	position: map.getCenter(),
    	map: map
       });
    }
    // call the function
       load();
    //]]>
    </script>
    <?php
    }
    else { echo "map not found"; }
    ?> 
    
    </div>
    <?php
    
    //Display the footer
    get_footer();
    ?>

    [Moderator Note: Please post code or markup between backticks or use the code button. Or better still - use a pastebin. Your posted code may now have been permanently damaged by the forum's parser.]

  7. LeRedac
    Member
    Posted 1 year ago #

    Hi James,

    are you sure the value get_field('laama_map'); is not empty ?

    Try this code for testing return value :

    echo '<pre>';
        print_r( get_field('laama_map')  );
    echo '</pre>';
  8. Extelliqent
    Member
    Posted 1 year ago #

    The code works perfect. I'd like to know if there is a way to make it so when you click the marker it opens up options like directions.

  9. JuNky3
    Member
    Posted 11 months ago #

    Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks! Thanks!

  10. mrwd
    Member
    Posted 11 months ago #

    Thank you so much to LeRedac & jamesfirass!
    And +1 to joshmaxrubinstein (I don't why ACF documentation is not using this code example).

  11. S_N_E_J_K_A
    Member
    Posted 10 months ago #

    Thanks! :)

  12. jamesfirass
    Member
    Posted 10 months ago #

    You guys are more than welcome!

  13. helln06
    Member
    Posted 10 months ago #

    Hey,

    thank you so much for this code... So helpfull !!

    Maybe you know how I could display multiple markers on a single map ?

    txs

  14. vijayrajesh
    Member
    Posted 9 months ago #

    Thank you so much :)

  15. bravenewniche
    Member
    Posted 7 months ago #

    Bacon saved - thanks!!

  16. LeRedac
    Member
    Posted 7 months ago #

    Ok this exemple if you whant display on a wordpress page, a Google Maps whith Multiple Markers (working whith WordPress 4.0 )

    This is my method, not sur it's the best ! Trie.

    Is working if you make a custom post type like "Map" and add custom field google map white ACF

    1- Make a new templates page >> Exemple PAGE name >> MAP in your theme >> page-map.php
    2 - Create a new page in WordPress dashboard >> Exemple >> MAP
    3- d'ont forget put on your header google map script

    <script src="http://maps.google.com/maps/api/js?sensor=false"
              type="text/javascript"></script>

    4 - Choice your template page >> MAP
    5 - Publish your page and see result

    This is exemple off MAP page (put your <div> inside)

    <?php
    /*
    Template Name: MAP
    */
    get_header();
    ?>
    <h1><?php the_title(); ?></h1>
    
    <section>
    
    <?php
      $args = array(
    	  'post_type'		=> 'YOUR_CUSTOM_POST_TYPE',
    	  'posts_per_page'	=> -1
      );
    // query
    $wp_query = new WP_Query( $args );
    $NUM = 0;
    ?>
    
      <div id="map" style="width: 500px; height: 400px;"></div>
    
    <script type="text/javascript">
        var locations = [<?php while( $wp_query->have_posts() ){
    	$wp_query->the_post();
        $location = get_field('carte_google'); // IMPORTANT << Change this for your Google map field name !!!!!!
    ?>
    
    ['<?php the_title(); ?>', <?php echo $location['lat']; ?>, <?php echo $location['lng'];?>, <?php $NUM++ ?>],
       <?php } ?> ];
    
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 9, /*Here you change zoom for your map*/
          center: new google.maps.LatLng(-21.1, 55.6), /*Here you change center map first location*/
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
    
        var infowindow = new google.maps.InfoWindow();
    
        var marker, i;
    
        for (i = 0; i < locations.length; i++) {
          marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map
          });
    
          google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
              infowindow.setContent(locations[i][0]);
              infowindow.open(map, marker);
            }
          })(marker, i));
        }
     </script>
    </section>
    <?php get_footer(); ?>
  17. ikyo
    Member
    Posted 6 months ago #

    Merci infiniment leRedac !!!
    Thank you so much !!

  18. selfagency
    Member
    Posted 5 months ago #

    how do you do this if it's not a custom post type but just advanced custom fields on a single page?

  19. LeRedac
    Member
    Posted 5 months ago #

    selfagency it's same, just put a code in your single.php and d'ont forget add this directly inside or in your header.php >>

    <script src="http://maps.google.com/maps/api/js?sensor=false"
              type="text/javascript"></script>

    If you whant display map on a specific single page , use Function Reference/is single

    Sorry people, my english is bad ;-)

  20. sabrina.zeidan
    Member
    Posted 5 months ago #

    LeRedac, grand merci! Thank you very much!

  21. dev.james
    Member
    Posted 4 months ago #

    Hey LeRedac, thanks a bunch for this code, looks like everyone is getting great use of it.

    I'm having trouble however. Please help me to resolve this, I've been plugging away all morning to no avail.

    The page I'm working on is: http://dev.captiv8.co.nz/contact/

    Here's all my code from my PHP:

    <?php /* Template Name: 1.4. Contained Width - Contact */
    
    get_header(); ?>
    
    	<div id="primary" class="content-area">
    		<main id="main" class="site-main" role="main">
    
            	<div id="custom-fields-full-width">   
    
      				<p class="custom-fields-page-heading">
    					<?php the_field('page_heading'); ?>
    				   	</p>	
    
                	<p class="custom-fields-intro-text">
    					<?php the_field('intro_paragraph'); ?>
    					</p>
    
    				<p class="custom-fields-body-text">
    					<?php the_field('body_text'); ?>
         				</p>       
    
                  <div id="view1">
                     	<?php $location = get_field('google-map');
                      if( ! empty($location) ):
                      ?>
    
                        	<div id="map" style="width: 100%; height: 350px;">
                        		</div>
    
    						<script src='http://maps.googleapis.com/maps/api/js?sensor=false' type='text/javascript'></script>
    
                        	<script type="text/javascript">
    
    							//<![CDATA[
                           	function load() {
    
    								var lat = <?php echo $location['lat']; ?>;
                              	var lng = <?php echo $location['lng']; ?>;
    
    							// coordinates to latLng
                              	var latlng = new google.maps.LatLng(lat, lng);
    
    							// map Options
                              	var myOptions = {
                              	zoom: 9,
                              	center: latlng,
                              	mapTypeId: google.maps.MapTypeId.ROADMAP
                              	};
    
    							//draw a map
                              	var map = new google.maps.Map(document.getElementById("map"), myOptions);
                              	var marker = new google.maps.Marker({
                              	position: map.getCenter(),
                              	map: map
                              	});
                          	}
    
                            	// call the function
                           	load();
    
                          //]]>
                       	</script>
    
                       <?php endif; ?>    
    
                  	</div> <!--view1 div--> 
    
    			</div> <!--custom-fields-full-width div-->
    
    		</main><!-- .site-main -->
    
    	</div><!-- .content-area -->
    
    <?php get_footer(); ?>

    I've also dropped the correct script code into the header.php file.

    Thanks in advance for your help,

    James

  22. LeRedac
    Member
    Posted 4 months ago #

    Hi James, are you sure the value >> get_field('google-map'); is not empty ?

    Try this code for testing return value :

    echo '<pre>';
        print_r( get_field('google-map')  );
    echo '</pre>';

    Inside ACF are you make a field whith name "google-map" ?

  23. LeRedac
    Member
    Posted 4 months ago #

    And for if you put :

    <script src='http://maps.googleapis.com/maps/api/js?sensor=false' type='text/javascript'></script>

    directly on the page template , is not nescesery put this in header.php

    Or

    if you put script on the header.php is not nescesery put this in your template page

  24. dev.james
    Member
    Posted 4 months ago #

    Hey LeRedac,

    Thanks for helping me out so quickly! I'll have a play and see what I can do.

    Appreciate your good work with helping everyone :)

    J

  25. brianj
    Member
    Posted 4 months ago #

    Bonjour LeRedac ,

    Do you know how to use this same method to show all icons/locations from each custom post on one google map?

    For example, I have a custom post type "Listings". Each listing post has a google map location added using advanced custom fields "Google Map" field. When viewing the listings page on the frontend showing all listings, I want a single Google Map to show locations from all listings.

    Thanks in advance for having a look

  26. LeRedac
    Member
    Posted 4 months ago #

    Hello Brianj , is it not the second method that could solve your problem ? The one I proposed in the above post ? >> Google Maps whith Multiple Markers

  27. LeRedac
    Member
    Posted 4 months ago #

    Or if you whant display Google Maps whith Multiple Markers from multiple custom post type, try use wp-query with array

    $args = array(
              'post_type' => array('YOUR_CUSTOM_POST_TYPE_NAME', 'SECOND_CUSTOM_POST_TYPE_NAME'),
    	  'posts_per_page'	=> -1
      );
  28. brianj
    Member
    Posted 4 months ago #

    I missed that code you posted, worked perfectly, thanks!

    I'm trying to add a list below the map so that links are clickable to open the bubble of the clicked location. Any idea how to get it working? Here's my code

    <div class="catlistingsmap">
    
    <div id="map" style="width: 500px; height: 400px;"></div>
    
    <script type="text/javascript">
    		var locations = [<?php while( $wp_query->have_posts() ){
    							$wp_query->the_post();
    							$location = get_field('google_map');
    						?>
    
    		['<?php the_title(); ?>', <?php echo $location['lat']; ?>, <?php echo $location['lng'];?>, <?php $NUM++ ?>],
    		<?php } ?> ];
    
    		gmarkers = [];
    
    		var map = new google.maps.Map(document.getElementById('map'), {
    			zoom: 9, /*Here you change zoom for your map*/
    			center: new google.maps.LatLng(26.4336571, -81.9250167), /*Here you change center map first location*/
    			mapTypeId: google.maps.MapTypeId.ROADMAP
    		});
    
    		var infowindow = new google.maps.InfoWindow();
    
    		var marker, i;
    
    		for (i = 0; i < locations.length; i++) {
    			marker = new google.maps.Marker({
    			position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    			map: map
    		});
    
    		google.maps.event.addListener(marker, 'click', (function(marker, i) {
    			return function() {
    			infowindow.setContent(locations[i][0]);
    			infowindow.open(map, marker);
    			}
    		})(marker, i));
    		}
    
    </script>
    
    <a href="javascript:google.maps.event.trigger(gmarkers['<?php the_title(); ?>'],'click');" class="button3"><?php the_title(); ?></a>
    
    </div>

    Found this jsfiddle with clickable links, but the trigger isn't working for me. http://jsfiddle.net/RASG/X5mhL/

    UPDATE: Got it working , just had to move gmarkers[locations[i][0]] =

    Thanks

  29. LeRedac
    Member
    Posted 4 months ago #

    Try to see and use Google map API >>

    https://developers.google.com/maps/documentation/javascript/examples/infowindow-simple

    I try the make same fonction for the futur ;-)
    I'm come back here if is work for me

    By

  30. Fabio Marzocca
    Member
    Posted 3 months ago #

    Geat job LeRedac!!!

    If you want to add links to your posts in the multiple markers, just replace this line:

    ['<?php the_title(); ?>', <?php echo $location['lat']; ?>, <?php echo $location['lng'];?>, <?php $NUM++ ?>],
    		<?php } ?> ];

    with this new one:

    ['<?php echo("<a href=\"".get_the_permalink()."\" >".get_the_title()."</a>"); ?>', <?php echo $location['lat']; ?>, <?php echo $location['lng'];?>, <?php $NUM++ ?>],
       <?php } ?> ];

    Fabio

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags