Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Custom fields and Google Map

Posted on 2014-01-11
8
1,107 Views
Last Modified: 2014-01-20
Dear experts,

I am using Advance Custom Fields plugin to create some custom fields on my new custom post type. One of the things Iwould like to do is to have  a google map APi to display all the address that are stored on my custom fields. I am not a pro in coding so it is taking me quite long to figure this out and my deadline is so close….

I am using an add-on from advance custom field plugin named Google Maps, which allows me to place a google map into each post (still figuring this out, but I will leave that for later). For now I just need to display a map that marks all the addresses from each custom post type.

Here is the code I am using to display the custom fields. As you can see from the code, there is a custom field named address. how can I collect all those addresses to place a marker in a google maps?

remove_action('genesis_loop', 'genesis_do_loop');//remove genesis loop
add_action('genesis_loop', 'places_loop');//add the special loop
 
function accommodations_loop() {
    $loop = new WP_Query( array( 'post_type' => 'places', 'posts_per_page' => 4, 'paged' => get_query_var( 'paged' ) ) ); ?>
                <h1><?php the_title(); ?></h1>
            <div id="places">
                      <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
                              <div class="places">
                                    <h3><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
                                    <div id="post-<?php the_ID(); ?>" class="list">
                              <?php//use the genesis_get_custom_field template tag to display each custom field value ?>
                                    <div><?php echo the_post_thumbnail('custom-thumb-1'); ?></div>
                              <div><?php echo the_field('intro_text'); ?></div>
                                    <div><?php echo the_field('address'); ?></div>
                              <div><?php echo the_field('phone_number'); ?></div>
                              <div><?php echo the_field('website'); ?></div>
                        </div><!--end #specials -->
                  </div>
    <?php endwhile;?>
 <?php
}
 genesis();

I would really appreciate any help. Thanks
0
Comment
Question by:glepiza
  • 4
  • 3
8 Comments
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39774857
This is not specific to Wordpress, but it's probably background information you would want to understand if you're getting into using Google Maps.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_3350-Using-the-Google-Maps-API-in-PHP.html
0
 
LVL 38

Expert Comment

by:Tom Beck
ID: 39790599
Did you get this resolved?
0
 

Author Comment

by:glepiza
ID: 39791631
not yet :(. Still looking...
0
Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 38

Accepted Solution

by:
Tom Beck earned 400 total points
ID: 39791691
Here is something to try. Declare a php array to hold the addresses at the beginning of your loop. Then collect the addresses in the array.

...
<?php $addresses = array(); while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php $address = $wpdb->get_var("SELECT meta_value FROM wp_postmeta WHERE post_id=$post->ID AND meta_key='Address'");
          array_push($addresses, $address); ?>

...

Then, right after the end of the loop add a div to hold the map (you can move it later).

...
<?php endwhile; ?>            
<div id="map-canvas" style="width:400px;height:300px"></div>
...

Just below that, place the javascript to load the map with the geocoded markers.
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&v=3&libraries=geometry" type="text/javascript"></script>
			<script type="text/javascript">
			var locations = <?php echo json_encode($addresses); ?>;
			if (locations.length > 0) {
				var bounds = new google.maps.LatLngBounds();
				var geocoder = new google.maps.Geocoder();
				var startingPoint = new google.maps.LatLng(41.88318,-87.63173);
		    var mapOptions = {
            	zoom: 15,
                center: startingPoint,
                mapTypeId: google.maps.MapTypeId.ROADMAP
             }

             var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
             var marker = new google.maps.Marker({
                map: map,
                icon: "http://www.conceptfire-uk.com/wp-content/uploads/2011/07/icon-pin-color.png",
                position: startingPoint
             });

            var chunk = 0;
			// muliple location geocoding needs to be done on a delay as Google restricts the number of
			// consecutive geocode requests
            var interval = setInterval(function() {delayCode();}, 700);
            function delayCode() {
                  var step = 1;
                  if (chunk < locations.length) {
                        for (x = chunk; x < locations.length && x < chunk + step; x++) {
                              codeAddress(locations[x]);
                        }
                        chunk += step;
                  } else{
                        clearInterval(interval);
                  }
            }

            function codeAddress(address) {
			   if (address !== '') {
                  geocoder.geocode({ 'address': address }, function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                        	addressLoc = results[0].geometry.location;		
			   	            createMarker(addressLoc, address);
                        }
                        else {
                            console.log('Geocode was not successful for the following reason: ' + status);
                        }
                  });
			   } 
            }

			function createMarker(loc, address){
				var marker = new google.maps.Marker({map: map, position: loc});
				var infowindow = new google.maps.InfoWindow();
			      google.maps.event.addListener(marker, "click", function () {
                	  infowindow.setContent('<b>' + address + '</b>');
                	  infowindow.open(map, this);
            	  }); 
				  //extend the bounds of the map to include all the markers and the starting point
				  bounds.extend(loc);
				  
				  //zoom the map to nicely fit the bounds of the markers
                  map.fitBounds(bounds);
			}
			}
            </script>

Open in new window

I have no way of testing it with your loop and your custom fields, but it worked in my simple test.
0
 
LVL 38

Expert Comment

by:Tom Beck
ID: 39792106
Looks like your field named "address" is lower case so be sure to adjust that in the sql statement.
meta_key='address' instead of meta_key='Address'
0
 

Author Comment

by:glepiza
ID: 39794221
Tom, you are a genius!!, thank you very much. Sorry for taking too much time answering, I got couple of stuff in my website, so I needed to fix that first but it took me so long….

Thank you again!!!!


Winter
0
 

Author Closing Comment

by:glepiza
ID: 39794222
Thank you!!!!!!!!!!!
0
 
LVL 38

Expert Comment

by:Tom Beck
ID: 39794480
You're welcome. That worked right out of the box? Pleasant surprise.

I have this as the starting point in the javascript:
var startingPoint = new google.maps.LatLng(41.88318,-87.63173);
Which I think is somewhere in Chicago so you might want to change that to something local for you. If the geocoding were to fail, you would be displaying a map of part of Chicago on your site.

Thanks for the points.
0

Featured Post

Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The purpose of this video is to demonstrate how to reset a WordPress password if you are locked out and cannot reset the password. A typical use would be if you cannot access the email to which WordPress would send the password recovery email to…
The purpose of this video is to demonstrate how to prevent comment spam on a WordPress Website. This will be demonstrated using a Windows 8 PC. Plugin Akismet will be used. Go to your WordPress login page. This will look like the following: myw…

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question