paullacey78
8/2/2017 - 12:52 AM

Adds a google map to a post using coordinates from custom fields

Adds a google map to a post using coordinates from custom fields

<?php
/** 
 * Google maps shortcode
 *
 * Adds a google map to a post using coordinates from custom fields
 *
 * @return string HTML to show a Google map
 */

function bd_map_sc($atts) {

	global $post;
	$post_id = $post->ID;

	$location = get_post_meta($post_id, 'your-custom-field-name', true);
	$lat = $location['lat']; 
	$lng = $location['lng'];

   	$map = '<style>
       #map {
        height: 400px;
        width: 100%;
       }
    </style>

	<div id="map"></div>

    <script>
      function initMap() {
	var map_coords = {lat: ' . $lat . ', lng: ' . $lng . '};
        var map = new google.maps.Map(document.getElementById("map"), {
          zoom: 14,
          center: map_coords
        });
        var marker = new google.maps.Marker({
          position: map_coords,
          map: map
        });
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=ADD-YOUR-GOOGLE-MAPS-API-KEY-HERE&callback=initMap">
    </script>';

	return $map;
  
}
add_shortcode('bd_map', 'bd_map_sc');