0

I am getting one map marker to display but not multiple markers. However the data displays in the HTML log. I think I am missing a loop or did not use my current loop correctly. Anyone who could clarify would make my day. Thank you. Herewith the code:

<h1 class="entry-title">Find a store</h1>
<script type="text/javascript">
var map;
    function initMap() {
            map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: -28.5758488, lng: 25.1128267},
            zoom: 5
        });
        setMarkers(map);
};

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

<?php
    $args = array('post_type' => 'store', array("output"=>"raw"), 'posts_per_page' => 50,);
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
?>

<?php $lat = types_render_field("lat", array("output"=>"raw")); ?>
<?php $long = types_render_field("long", array("output"=>"raw")); ?>

<script type="text/javascript">
    var lat = <?php echo $lat; ?>;
    var long = <?php echo $long; ?>;
    var locations = [
        ['<?php the_title(); ?>', lat, long]
    ];

    function setMarkers(map) {
        for (var i = 0; i < locations.length; i++) {
            var location = locations[i];
            var marker = new google.maps.Marker({
                position: {lat: location[1], lng: location[2]},
                map: map,
                title: location[0],
            });
        }
    }
</script>

This is the output script within the console log:

<script type="text/javascript">
var map;
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -28.5758488, lng: 25.1128267},
    zoom: 5
    });
setMarkers(map);
};

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



    <script type="text/javascript">
        function setMarkers(map) {
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng({lat: -25.746111, lng: 28.188056}),
                    map: map,
                    title: 'Willow Way Spar'
                });
            }
    </script>



    <script type="text/javascript">
        function setMarkers(map) {
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng({lat: -29.919885, lng: 30.941782}),
                    map: map,
                    title: 'Yellowwood park Superspar'
                });
            }
    </script>



    <script type="text/javascript">
        function setMarkers(map) {
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng({lat: -26.8598225, lng: 26.6317514}),
                    map: map,
                    title: 'Zest for Health'
                });
            }
    </script>



    <script type="text/javascript">
        function setMarkers(map) {
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng({lat: -25.8299422, lng: 28.2819103}),
                    map: map,
                    title: 'Zest Wellness Centre'
                });
            }
    </script>

...and I get the same result with this code:

<?php get_header(); ?>
<!-- Row for main content area -->
<div class="small-12 large-12 columns" id="content" role="main">

<h1 class="entry-title">Find a store</h1>

<script type="text/javascript">
var map;
    function initMap() {
            map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: -28.5758488, lng: 25.1128267},
            zoom: 5
        });
        setMarkers(map);
};

<?php
    $args = array('post_type' => 'store', array("output"=>"raw"), 'posts_per_page' => 50,);
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
?>

<?php $lat = types_render_field("lat", array("output"=>"raw")); ?>
<?php $long = types_render_field("long", array("output"=>"raw")); ?>

<script type="text/javascript">
    var lat = <?php echo $lat; ?>;
    var long = <?php echo $long; ?>;
</script>

    <script>
        function setMarkers(map) {
                var marker = new google.maps.Marker({
                    position: {lat: lat, lng: long},
                    map: map,
                    title: '<?php the_title(); ?>',
                });
            }
    </script>

<?php wp_reset_postdata(); ?>

Herewith a link to the test page: http://www.golonutrition.co.za/find-a-store/

With your help Dan, I tried using it like this but obviously I am missing the point somewhere...

<?php get_header(); ?>

<!-- Row for main content area -->
<div class="small-12 large-12 columns" id="content" role="main">

<h1 class="entry-title">Find a store</h1>

<?php
    $storeData = [];

    foreach ( $loop->posts as $post ) {
            $storeData[] = [
                    'title' => apply_filters('the_title', $post->post_title),
                    'lat'   => types_render_field('lat', array('output'=>'raw')),
                    'long'  => types_render_field('long', array('output'=>'raw'))
            ];
    }

    wp_localize_script('jquery-core', 'storeData', $storeData);
?>

<script type="text/javascript">
    var map;
        function initMap() {
                map = new google.maps.Map(document.getElementById('map'), {
                center: {lat: -28.5758488, lng: 25.1128267},
                zoom: 5
            });
            setMarkers(map);
    };
</script>

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

    <?php
        $args = array('post_type' => 'store', array("output"=>"raw"));
        $loop = new WP_Query( $args );
        while ( $loop->have_posts() ) : $loop->the_post();
    ?>

    <?php $lat = types_render_field("lat", array("output"=>"raw")); ?>
    <?php $long = types_render_field("long", array("output"=>"raw")); ?>

    <script type="text/javascript">
        function setMarkers(map) {
        for (var i=0; i<i; i++) {
            var marker=new google.maps.Marker({
                    position: new google.maps.LatLng({lat: storeData[i].lat, lng: storeData[i].long}),
                    map: map,
                    title: storeData[i].title
            });
    }
}
    </script>

<?php endwhile; ?>

        <script src="https://maps.googleapis.com/maps/api/..." async defer></script>

</div>

The updated code as per Dan. (Although still one small error: InvalidValueError: in property lat: not a number)

<?php
$storeData = [];
$args = array('post_type' => 'store');
$loop = new WP_Query($args);
foreach ( $loop->posts as $post ) {
    $storeData[] = [
        'title' => apply_filters('the_title', $post->post_title),
        'lat'   => types_render_field('lat', array('output'=>'raw')),
        'long'  => types_render_field('long', array('output'=>'raw'))
    ];
}
wp_localize_script('jquery-core', 'storeData', $storeData);?>

<?php get_header(); ?>

<!-- Row for main content area -->
<div class="small-12 large-12 columns" id="content" role="main">

<h1 class="entry-title">Find a store</h1>

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

        <script src="https://maps.googleapis.com/maps/api/..." async defer></script>

<script type="text/javascript">
    var map;
    function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: -28.5758488, lng: 25.1128267},
            zoom: 5
        });
        var j = storeData.length;
        for (var i=0; i<j; i++) {
            var marker=new google.maps.Marker({
                position: new google.maps.LatLng({lat: storeData[i].lat, lng: storeData[i].long}),
                map: map,
                title: storeData[i].title
            });
        }
    };
</script>

0

Update 2:

<?php
$storeData = [];
$args = ['post_type' => 'store'];
$loop = new WP_Query($args);
foreach ($loop->posts as $post) {
    $storeData[] = [
        'title' => apply_filters('the_title', $post->post_title),
        'lat' => types_render_field('lat', ['output' => 'raw']),
        'long' => types_render_field('long', ['output' => 'raw']),
    ];
}
wp_localize_script('jquery-core', 'storeData', $storeData);
?>

<?php get_header(); ?>

<!-- Row for main content area -->
<div class="small-12 large-12 columns" id="content" role="main">

<h1 class="entry-title">Find a store</h1>

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

    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB2ealUwmPEEdwZXFBAAcc7tiQLAl-Tys4&callback=initMap" async defer></script>

    <script type="text/javascript">
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 5,
            center: new google.maps.LatLng(-27.2758488, 26.1128267),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        var infowindow = new google.maps.InfoWindow();
        var marker, i;
        var j = storeData.length;
        function initMap() {
            for (i = 0; i < j; i++) {
                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(storeData[i].lat, storeData[i].long),
                    map: map
                });

                google.maps.event.addListener(marker, 'click', (function(marker, i) {
                    return function() {
                        infowindow.setContent(storeData[i].title);
                        infowindow.open(map, marker);
                    }
                })(marker, i));
            }
        };
    </script>

</div>

<?php get_footer(); ?>

Update 1:

This is all you need:

<?php
$storeData = [];
$args = array('post_type' => 'store');
$loop = new WP_Query($args);
foreach ( $loop->posts as $post ) {
    $storeData[] = [
        'title' => apply_filters('the_title', $post->post_title),
        'lat'   => types_render_field('lat', array('output'=>'raw')),
        'long'  => types_render_field('long', array('output'=>'raw'))
    ];
}
wp_localize_script('jquery-core', 'storeData', $storeData);
?>

<?php get_header(); ?>

<!-- Row for main content area -->
<div class="small-12 large-12 columns" id="content" role="main">

<h1 class="entry-title">Find a store</h1>

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

    <script src="https://maps.googleapis.com/maps/api/..." async defer></script>

    <script type="text/javascript">
        var map;
        function initMap() {
            map = new google.maps.Map(document.getElementById('map'), {
                center: {lat: -28.5758488, lng: 25.1128267},
                zoom: 5
            });
            var j = storeData.length;
            for (var i=0; i<j; i++) {
                var marker=new google.maps.Marker({
                    position: new google.maps.LatLng({lat: storeData[i].lat, lng: storeData[i].long}),
                    map: map,
                    title: storeData[i].title
                });
            }
        };
    </script>

</div>

Problem: In initMap() callback, you call setMarkers(map) only once. But inside the loop, you have more than one setMarkers(map) function. Then only the last setMarkers(map) function will be called by initMap() which displays the last store only.

Solution: The best solution is using wp_localize_script() to localize stores' data to a registered script:

You must do this at the beginning of the template:

$storeData = [];

foreach ($loop->posts as $post) {
    $storeData[] = [
        'title' => apply_filters('the_title', $post->post_title),
        'lat'   => types_render_field('lat', array('output'=>'raw')),
        'long'  => types_render_field('long', array('output'=>'raw'))
    ];
}

wp_localize_script('jquery-core', 'storeData', $storeData);

Now, inside initMap() function, render each store data in storeData array:

for (var i=0; i<j; i++) {
    var marker=new google.maps.Marker({
        position: new google.maps.LatLng({lat: storeData[i].lat, lng: storeData[i].long}),
        map: map,
        title: storeData[i].title
    });
}
| improve this answer | |
  • Thank you very much. Could I just ask about the structure of the code and what to throw out? I am just not sure how to incorporate this into the current structure as it is unfamiliar to me. – Ruan Petersen Apr 25 '16 at 10:44
  • I've tried this; but to no avail... (added to post) – Ruan Petersen Apr 25 '16 at 10:54
  • @RuanPetersen I have just updated the answer. – SarahCoding Apr 25 '16 at 11:17
  • Utter genius. Thank you. However this is still giving me a headache and I hate to make it yours but would you mind checking the console error on the page? I've had this error before but because of different reasons so I am not sure of the exact cause... – Ruan Petersen Apr 25 '16 at 12:19
  • @RuanPetersen Well, The errors caused by lat: is not a valid value. You should change lat: and lng: to actual values. Update 2: I have done all jobs, just copy and paste the code in your template. It should work. – SarahCoding Apr 25 '16 at 15:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.