I am trying to fetch the lat, long data from custom fields in my posts in order to make a map layer with them (openlayers).
- I added custom long and lat fields to each post
- I created a function to fetch this data
- I enqueued scripts in my functions.php
I want to access this data in another script (travel-map.js) but window.mapData remains not available. How can I make this data accessible in my Javascript script?
Thank you
functions.php
function enqueue_fetch_data_from_posts() {
wp_enqueue_script( 'fetch-data-from-posts', get_stylesheet_directory_uri() . '/assets/js/fetch-data-from-posts.js', array('openlayers'), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'enqueue_fetch_data_from_posts' );
//Query data from all the posts
function map_data() {
$args = array(
'meta_key' => 'latitude',
'meta_value' => '', // We only need posts with a value
'meta_compare' => '!='
);
$posts = get_posts($args);
$markers = array();
foreach ($posts as $post) {
$lat = get_post_meta($post->ID, 'latitude', true);
$lng = get_post_meta($post->ID, 'longitude', true);
if (is_numeric($lat) && is_numeric($lng)) {
$markers[] = array(
'lat' => $lat,
'lng' => $lng,
'link' => get_permalink($post->ID), // Link to the blog post
'title' => $post->post_title // Optional: Title for tooltip
);
echo '<script>console.log("Marker Data:", ' . json_encode($markers) . ');</script>';
}
}
wp_localize_script('travel-map-script', 'mapData', $markers);
}
add_action( 'wp_enqueue_scripts', 'map_data' );
function enqueue_travel_map_script() {
wp_enqueue_script( 'travel-map-script', get_stylesheet_directory_uri() . '/assets/js/travel-map.js', array('openlayers'), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'enqueue_travel_map_script' );
travel-map.js
// Create markers for blog posts
var markers = [];
console.log("window.mapData:", window.mapData); // Check the value here
if (window.mapData && window.mapData.length > 0) {
for (var i = 0; i < window.mapData.length; i++) {
var marker = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([window.mapData[i].lng, window.mapData[i].lat])),
});
marker.set('title', window.mapData[i].title); // Optional: Set title for tooltip
marker.set('link', window.mapData[i].link);
});
}
} else {
console.warn("window.mapData is not available or empty. Skipping marker creation.");
}