Created
July 22, 2015 10:38
-
-
Save ditikos/24d6f57c4fc8a6471891 to your computer and use it in GitHub Desktop.
Load Google maps in multiple posts/pages/cpt using lat/lng as custom fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// PREREQUISITES | |
1. Google API Maps Browser Key | |
// NOTE: The following example assumes you are using posts in the front page (like twentyfifteen theme). | |
// Change when needed. | |
// Style.css: | |
Add the direction: | |
.maps { height: 40vh; width: 100%; } | |
// Functions.php | |
Add the following: | |
function wp_google_scripts() { | |
global $post; | |
$API_KEY = ** API KEY FROM GOOGLE **; | |
wp_enqueue_script( 'google-maps-native', "http://maps.googleapis.com/maps/api/js?key=".$API_KEY); | |
} | |
add_action( 'wp_enqueue_scripts', 'wp_google_scripts' ); | |
// Footer.php #1 | |
Add the following in the start of the file: | |
<?php global $post; ?> | |
OR if there are more globals, add $post at the end. | |
// Footer.php #2 | |
Add the following (before wp_footer() for now *will update*) | |
<?php | |
$args = array( | |
'post_type'=>array('post','page','product'), // product is an example custom post type add remove the posts you want. | |
'post_status'=>'publish', | |
'meta_query' => array( | |
array( | |
'key' => 'lng', | |
'compare' => 'EXISTS', | |
), | |
array( | |
'key' => 'lat', | |
'compare' => 'EXISTS', | |
), | |
), | |
); | |
$maps = new WP_Query($args); | |
if ($maps->have_posts()): ?> | |
<script type="text/javascript"> | |
function initialize() { | |
<?php | |
while ($maps->have_posts()): | |
$maps->the_post(); | |
$lat = get_post_meta(get_the_ID(),'lat',true); | |
$lng = get_post_meta(get_the_ID(),'lng',true); | |
?> | |
var mapOptions<?php echo get_the_ID(); ?> = { | |
center: { lat: <?php echo $lat; ?>, lng: <?php echo $lng; ?>}, | |
zoom: 3 | |
}; | |
var map<?php echo get_the_ID(); ?> = new google.maps.Map(document.getElementById('map_<?php echo get_the_ID(); ?>'),mapOptions<?php echo get_the_ID(); ?>); | |
<?php | |
endwhile; | |
?> | |
} | |
google.maps.event.addDomListener(window, 'load', initialize); | |
</script> | |
<?php | |
endif; | |
wp_reset_postdata(); | |
?> | |
// In your POST, PAGE or CPT add two custom fields lat, lng. lat is LATITUDE, lng is LONGITUDE. | |
// In your display, for twentyfifteen is content.php add the following after the "the_content(...); " directive: | |
$lat = get_post_meta(get_the_ID(),"lat",true); | |
$lng = get_post_meta(get_the_ID(),"lng",true); | |
if (!empty($lat) && !empty($lng)) { | |
?> | |
<div class="maparea" id="map_<?php echo get_the_ID(); ?>"></div> | |
<?php | |
// This will render maps in every post in index.php |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment