Get map field meta data (lang and long)
Support › MB Custom Post Type › Get map field meta data (lang and long)
- This topic has 1 reply, 2 voices, and was last updated 2 years ago by
Peter.
-
AuthorPosts
-
August 10, 2024 at 11:09 PM #46132
Mats Lindström
ParticipantHi. This code works great to show markers from my lat and long field. Now, how do instead use the coordinates direct from my map field?
function display_google_map() {
// Hämta alla inlägg från Custom Post Type 'stationer'
$stations = new WP_Query(array('post_type' => 'station', 'posts_per_page' => -1));
?>
<div id="map" style="width: 100%; height: 500px;"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAdc9p_FnrdVKuIW-txjCmc6s429pKBcj0"></script>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: 59.3293, lng: 18.0686} // Stockholm som centrering
});var markers = [
<?php
if ($stations->have_posts()) :
while ($stations->have_posts()) : $stations->the_post();
// Hämta lat och long från de separata fälten
$latitude = get_post_meta(get_the_ID(), 'lat', true);
$longitude = get_post_meta(get_the_ID(), 'long', true);
if ($latitude && $longitude) {
echo "{lat: $latitude, lng: $longitude, title: '" . get_the_title() . "'},";
}
endwhile;
wp_reset_postdata();
endif;
?>
];markers.forEach(function(marker) {
new google.maps.Marker({
position: {lat: marker.lat, lng: marker.lng},
map: map,
title: marker.title
});
});
}window.onload = initMap;
</script>
<?php
}
add_shortcode('google_map', 'display_google_map');August 12, 2024 at 10:40 PM #46138Peter
ModeratorHello Mats,
If you use the map field, you can follow the documentation below to get the map data: latitude, longitude
https://docs.metabox.io/fields/map/#getting-field-value$location = rwmb_get_value( 'map_field_id', '', get_the_ID() ); $latitude = $location['latitude']; $longitude = $location['longitude']; -
AuthorPosts
- You must be logged in to reply to this topic.