Skip to content

Instantly share code, notes, and snippets.

@Jimmi08
Forked from farichello/WP posts on map
Created January 7, 2025 13:16
Show Gist options
  • Save Jimmi08/12e05a6558d16720912bcc40e129987e to your computer and use it in GitHub Desktop.
Save Jimmi08/12e05a6558d16720912bcc40e129987e to your computer and use it in GitHub Desktop.
WP posts on map
// SCF Google Map API Key
function my_acf_init() {
acf_update_setting('google_api_key', 'YOUR_API_KEY');
}
add_action('acf/init', 'my_acf_init');
function us_portfolio_google_map_shortcode() {
// Getting an API key
$google_api_key = acf_get_setting('google_api_key');
// Getting all posts of type 'us_portfolio' with the field 'address' filled in
$posts = new WP_Query([
'post_type' => 'us_portfolio',
'posts_per_page' => -1,
'meta_query' => [
[
'key' => 'address',
'compare' => 'EXISTS',
],
],
]);
// Create an array of markers to pass to JavaScript
$markers = [];
if ($posts->have_posts()) {
while ($posts->have_posts()) {
$posts->the_post();
$address_field = get_field('address'); // Getting ACF data from Google Map field
if (!empty($address_field) && isset($address_field['lat'], $address_field['lng'])) {
$markers[] = [
'title' => get_the_title(),
'lat' => floatval($address_field['lat']),
'lng' => floatval($address_field['lng']),
'image' => get_the_post_thumbnail_url(get_the_ID(), 'thumbnail'), // Post image URL
'link' => get_permalink(), // Link to post
];
}
}
wp_reset_postdata();
}
// If the markers are empty, we display an error message
if (empty($markers)) {
return '<p>No data available to display on the map. Please check if the addresses in us_portfolio posts are filled.</p>';
}
// Insert map style
$map_style = '[
{
"featureType": "water",
"elementType": "geometry",
"stylers": [
{
"color": "#e9e9e9"
},
{
"lightness": 17
}
]
},
{
"featureType": "landscape",
"elementType": "geometry",
"stylers": [
{
"color": "#f5f5f5"
},
{
"lightness": 20
}
]
},
{
"featureType": "road.highway",
"elementType": "geometry.fill",
"stylers": [
{
"color": "#ffffff"
},
{
"lightness": 17
}
]
},
{
"featureType": "road.highway",
"elementType": "geometry.stroke",
"stylers": [
{
"color": "#ffffff"
},
{
"lightness": 29
},
{
"weight": 0.2
}
]
},
{
"featureType": "road.arterial",
"elementType": "geometry",
"stylers": [
{
"color": "#ffffff"
},
{
"lightness": 18
}
]
},
{
"featureType": "road.local",
"elementType": "geometry",
"stylers": [
{
"color": "#ffffff"
},
{
"lightness": 16
}
]
},
{
"featureType": "poi",
"elementType": "geometry",
"stylers": [
{
"color": "#f5f5f5"
},
{
"lightness": 21
}
]
},
{
"featureType": "poi.park",
"elementType": "geometry",
"stylers": [
{
"color": "#dedede"
},
{
"lightness": 21
}
]
},
{
"elementType": "labels.text.stroke",
"stylers": [
{
"visibility": "on"
},
{
"color": "#ffffff"
},
{
"lightness": 16
}
]
},
{
"elementType": "labels.text.fill",
"stylers": [
{
"saturation": 36
},
{
"color": "#333333"
},
{
"lightness": 40
}
]
},
{
"elementType": "labels.icon",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "transit",
"elementType": "geometry",
"stylers": [
{
"color": "#f2f2f2"
},
{
"lightness": 19
}
]
},
{
"featureType": "administrative",
"elementType": "geometry.fill",
"stylers": [
{
"color": "#fefefe"
},
{
"lightness": 20
}
]
},
{
"featureType": "administrative",
"elementType": "geometry.stroke",
"stylers": [
{
"color": "#fefefe"
},
{
"lightness": 17
},
{
"weight": 1.2
}
]
}
]';
// Output the map container and the script
ob_start(); ?>
<div id="us-portfolio-google-map" style="width: 100%; height: 500px;"></div>
<script>
function initUsPortfolioMap() {
console.log('Initializing map...');
// Initialize a map centered on Bali
const map = new google.maps.Map(document.getElementById('us-portfolio-google-map'), {
center: { lat: -8.675629, lng: 115.2222568 }, // Map center - Bali
zoom: 12,
styles: <?php echo $map_style; ?>, // Applying the Snazzy Maps style
});
const markers = <?php echo json_encode($markers); ?>;
let currentInfoWindow = null; // Variable for storing the current InfoWindow
// Checking that the markers are not empty
if (markers.length === 0) {
console.error('There are no markers to display!');
} else {
markers.forEach(marker => {
if (marker.lat && marker.lng) {
// Create a marker
const mapMarker = new google.maps.Marker({
position: { lat: marker.lat, lng: marker.lng },
map: map, // Link the marker to the map
title: marker.title,
icon: {
url: "https://sensivity.ru/wp-content/uploads/2024/12/marker.svg", // Custom marker
scaledSize: new google.maps.Size(50, 50),
anchor: new google.maps.Point(25, 50),
}
});
// Contents for InfoWindow
const infoWindowContent = `
<div style="max-width: 250px; background-color: #231f20; color: #ffffff; border-radius: 8px; padding: 10px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);">
<a href="${marker.link}" target="_blank" style="text-decoration: none; color: #ffffff;">
<img src="${marker.image}" alt="${marker.title}" style="width: 100%; height: auto; border-radius: 8px; margin-bottom: 10px;">
<h4 style="padding-top: 0; margin: 0; font-size: 16px; text-align: center; color: #fff; ">${marker.title}</h4>
</a>
</div>
`;
// Create an InfoWindow
const infoWindow = new google.maps.InfoWindow({
content: infoWindowContent,
});
// Add a click handler to the marker
mapMarker.addListener('click', () => {
// Close the current window if it is open
if (currentInfoWindow) {
currentInfoWindow.close();
}
// Open a new window
infoWindow.open(map, mapMarker);
currentInfoWindow = infoWindow;
});
} else {
console.error('Incorrect coordinates for marker:', marker);
}
});
// Closing InfoWindow when clicking on another location on the map
map.addListener('click', () => {
if (currentInfoWindow) {
currentInfoWindow.close();
}
});
}
}
</script>
<!-- Loading the map with libraries and asynchronously to optimize performance -->
<script src="https://maps.googleapis.com/maps/api/js?key=<?php echo esc_attr($google_api_key); ?>&callback=initUsPortfolioMap&async=true&defer=true"></script>
<?php
return ob_get_clean();
}
add_shortcode('us_portfolio_google_map', 'us_portfolio_google_map_shortcode');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment