Skip to content

Instantly share code, notes, and snippets.

@CrisHazzard
Created July 5, 2016 14:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CrisHazzard/84bdd5b8855c2211e7c38990617a823a to your computer and use it in GitHub Desktop.
Save CrisHazzard/84bdd5b8855c2211e7c38990617a823a to your computer and use it in GitHub Desktop.
AJAX Lazy Load Google Maps After Page Load (doesn't affect initial page load)
jQuery( window ).load(function() {
// This jQuery event only triggers after the first time a user scrolls. Your map loads once they scroll. This only makes sense if the map is below the fold
jQuery( window ).one( "scroll", function() {
loadAPI();
});
<script>
function loadAPI()
{
var script = document.createElement('script');
script.src = 'https://www.google.com/jsapi?key=[your_key]]&callback=loadMaps';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
}
function loadMaps()
{
google.load('maps', '3', {callback: mapLoaded});
}
function mapLoaded()
{
//here you can be sure that maps api has loaded
//and you can now proceed to render the map on page
// do whatever map setup you need here
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: <?php the_field('lat'); ?>, lng: <?php the_field('lon'); ?>},
zoom: 12,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var ctaLayer = new google.maps.KmlLayer(
'<?php the_field('gpx_file'); ?>',
{
suppressInfoWindows: true,
map: map,
preserveViewport: false
});
ctaLayer.setMap(map);
var geocoder = new google.maps.Geocoder();
var address = '<?php echo $trailheadAddr; ?>';
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
icon: '<?php echo get_template_directory_uri(); ?>/img/parking.png',
animation: google.maps.Animation.DROP,
position: results[0].geometry.location
});
}
});
}
</script>
@CrisHazzard
Copy link
Author

Used to lazy load below the fold Google Maps that have hiking directions and hiking maps on my blog

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment