Get map field meta data (lang and long)

Support MB Custom Post Type Get map field meta data (lang and long)

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #46132
    Mats LindströmMats Lindström
    Participant

    Hi. 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');

    #46138
    PeterPeter
    Moderator

    Hello 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'];
Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.