I am trying to add multiple Google Maps within WordPress functions.php, yet only the last map is showing.
How can I show multiple maps? Is it possible to create a shortcode loop?
I've tried to replace var "map" with an $arg or a random ID without success.
add_shortcode( 'map', 'gmaps_map' );
function gmaps_map( $args ) {
$id = substr( sha1( "Google Map" . time() ), rand( 2, 10 ), rand( 5, 8 ) );
ob_start();
$args = shortcode_atts( array(
'lat' => '49',
'lng' => '9',
'zoom' => '12',
'height' => '300px',
'id' => '0'
), $args, 'map' );
?>
<div class='map' style='height:<?php echo $args['height'] ?>;' id='map-<?php echo $id ?>'></div>
<script type='text/javascript'>
var <?php echo $args['id'] ?>;
function initMap() {
map = new google.maps.Map(document.getElementById('map-<?php echo $id ?>'), {
center: {lat: <?php echo $args['lat'] ?>, lng: <?php echo $args['lng'] ?>},
zoom: <?php echo $args['zoom'] ?>
});
var image = new google.maps.MarkerImage("<?php echo get_template_directory_uri(); ?>/images/marker.png", null, null, null, new google.maps.Size(64,64));
var marker = new google.maps.Marker({
position: {lat: <?php echo $args['lat'] ?>, lng: <?php echo $args['lng'] ?>},
map: map,
icon: image, // null = default icon
animation: google.maps.Animation.DROP,
title: 'Hello World!'
});
}
</script>
<?php
$output = ob_get_clean();
return $output;
}
add_action( 'wp_enqueue_scripts', 'gmaps_enqueue_assets' );
function gmaps_enqueue_assets() {
wp_enqueue_script(
'google-maps',
'//maps.googleapis.com/maps/api/js?callback=initMap',
array(),
'1.0',
true
);
}