Multiple markers on a Google map from custom field of CPT entries in Oxygen

le 26/10/2021
JAG

In Australian Oxygen Users Facebook group, John asks:
Has anyone used the Google Map field from many CPT entries to place pins on a single Google Map? I’ve followed the instructions at WPDevDesign for a single map pin and this works really well. but wondered if this has been attempted for multiple pins from different Posts. If not, does anyone have any ideas how to do this? I’m thinking a loop to step through the CPT’s grab the google map field and apply it to the map. I think I can do the loop in a Code element on the page. thoughts?
In this members-only tutorial we shall

register a `temple` Custom Post Type
attach a custom field group to the above CPT having a `location` field of type “Google Map” using Advanced Custom Fields
create a Template for the CPT archive
add a Code Block in the Template with the necessary PHP, CSS and JS to loop through all the entries of the CPT, pull the location custom field’s latitude, longitude, address and have these rendered on a Google map as multiple markers.

to show a Google map with markers of the locations specified in all the CPT items.

When a marker is clicked:

Step 1
Obtain a Google Maps API key and paste it in Oxygen > Settings.
Step 2
Install and activate Custom Post Type UI.
Go to CPT UI > Add/Edit Post Types.
Add your desired post type. In this example, I have added it like so:

If you would like to display the map on the CPT archive page, scroll down to Settings section set Has Archive to True.
You may also want to set a custom archive slug.

Step 3
Install and activate ACF.
Note: I have used ACF Pro in my test site. Did not test this with the free version. I think it will work with the free version as well.
Go to Custom Fields > Add New.
Add a new field group having a location field of “Google Map” type.
Attach it to your CPT.

Step 4
Add as many CPT entries as you need.
Specify the address in the Location metabox.

Step 5
Go to Oxygen > Templates.
Add a new Template for your CPT archive.
You may have to a priority of 1 or higher if you have a generic Template that applies to all archives.

Edit it with Oxgyen.
a) Add a Section.
b) Add a Heading with your desired text (“Temples Around the World” in this example) inside the Section.
c) Add a Code Block below it.
Advanced > Size & Spacing > Width: 100%.
PHP & HTML:

have_posts() ) {
echo '

';
while ( $query->have_posts() ) {
$query->the_post();
// do something.
$location = get_field( 'location' ); ?>

';
} else {
// no posts found.
}

// Restore original Post Data.
wp_reset_postdata();
?>

Replace xxxx with your Google Maps API key.
Note: If you want to display the map on a page other than the CPT archive, use the following code instead:
// WP_Query arguments.
$args = array(
'post_type' => array( 'temple' ),
'posts_per_page' => -1,
);

// The Query.
$query = new WP_Query( $args );

// The Loop.
if ( $query->have_posts() ) {
echo '

';
while ( $query->have_posts() ) {
$query->the_post();
// do something.
$location = get_field( 'location' ); ?>

';
} else {
// no posts found.
}

// Restore original Post Data.
wp_reset_postdata();

Replace temple with your CPT name.
CSS:
.acf-map {
width: 100%;
height: 400px;
border: #ccc solid 1px;
margin: 20px 0;
}

/* fixes potential theme css conflict */
.acf-map img {
max-width: inherit !important;
}

JavaScript:
(function($) { /*
* new_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 new_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 );

// return
return 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
*/
// global var
var map = null;

$(document).ready(function(){

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

// create map
map = new_map( $(this) );

});

});
})(jQuery);

d) [Optional] If you want to display a grid of entries of the CPT below the map, add a Easy Posts element below the Code Block and configure it to your liking.
That’s it! Visit the CPT archive (yoursite.com/temples) to see this in action.
References:

Google Map

Google maps with multiple markers


https://wordpress.stackexchange.com/a/220624/14380

Nos experts se tiennent à votre disposition
pour répondre à vos questions et vous conseiller
dans votre projet digital.

Vous souhaitez développer une application ?

Envie d’échanger avec l’un de nos experts ? Besoin d’en savoir plus ?
En savoir plus

Recevez notre newsletter

La protection des données nous tient à cœur. JAG utilise les informations que vous fournissez afin de vous proposer des informations et du contenu pertinent sur nos produits et services. Vous pouvez vous désinscrire de ce type de communications à tout moment. Pour plus d'informations, consultez notre politique de confidentialité
© 2022 JAG Consulting, sas. Tous droits réservés.
© 2022 JAG Consulting, sas. Tous droits réservés.
4.8
Lire les 51 avis
google
Brieuc Pauly
08/09/2022

Créative, dynamique et très professionnelle, c'est à mon sens les piliers qui soutiennent cette équipe talentueuse ! Une agence à taille humaine qui privilégie la qualité et le résultat. Alors si vous souhaitez le meilleur pour votre communication adressez vous les yeux fermés à ces passionnés, plus que compétents ! (Translated by Google) Creative, dynamic and very professional, these are in my opinion the pillars that support this talented team! A human-sized agency that favors quality and results. So if you want the best for your communication, turn your eyes closed to these enthusiasts, who are more than competent!

google
Amaury Tardier
08/09/2022

Merci à Julien et son équipe, plus que satisfait par le travail fourni ! Je recommande vivement ! (Translated by Google) Thanks to Julien and his team, more than satisfied with the work provided! I highly recommend !

Ravi de travailler avec l'équipe JAG pour la gestion de mon site de e-Commerce. Equipe réactive et toujours pleine de bonnes idées pour améliorer les performances du site (Translated by Google) Glad to work with the JAG team for the management of my e-Commerce site. Responsive team always full of good ideas to improve the performance of the site

Merci à Julien pour son accompagnement dans mon projet, je recommande à 200% c est le Top (Translated by Google) Thanks to Julien for his support in my project, I recommend 200% it is the top

Excellente agence. Equipe est très pro, à l'écoute et de bon conseils. (Translated by Google) Excellent agency. The team is very professional, attentive and gives good advice.

Temps de réponse hors pair quand il y a eu un pb sur mon site, je vous recommande chaleureusement Julien :-) (Translated by Google) Unparalleled response time when there was a problem on my site, I warmly recommend Julien :-)

Charger plus
listarrow-right
Julien

Julien

Votre conseiller

I will be back soon

Une question ?

Julien
Bonjour ! Je suis Julien.
Comment puis-je vous aider?
Démarrer la conversation:
chat Live Chat