How do I create Google Map Markers From Custom Posts Loop

How do I loop through my wordpress custom post type (locations) and generate google map api markers for each post. I’m really bad at js syntax so any help would be greatly appreciated.

If I pull out the php locations loop for the markers everything works.

Here is what I have so far

<script type="text/javascript">

  var mapStyles= [];

  function initMap() {

    <?php 
      $latitude = "39.18624"; 
      $longitude = "-74.53448";
      $centeredLatitude = "39.18624"; 
      $centeredLongitude = "-75.53448";
    ?> 

    const map = new google.maps.Map(document.getElementById("map"), {
      zoom: 4,
      center: { lat:<?php echo $centeredLatitude; ?>, lng: <?php echo $centeredLongitude; ?> },
      styles: mapStyles,
    });
    
    const image ="footer-fish-icon-110.png";

    var marker = new google.maps.Marker({
      position: { lat:<?php echo $latitude; ?>, lng: <?php echo $longitude; ?> },
      map,
      icon: image,
    });

    <?php 
     // locations  loop for markers
      $args = array( 
        'orderby' => 'title',
        'order' => 'ASC',
        'post_type' => 'location', 
        'posts_per_page'=>-1
        );
      
      $locations = new WP_Query( $args );
   
      if( $locations->have_posts() ) {
        // looop through each location and create marker
        while( $locations->have_posts() ) {
          $location->the_post();
          $location_name = get_field('location_name');
          $latitude = get_field('latitude');
          $longitude = get_field('longitude');
          ?>

          var marker = new google.maps.Marker({
            position: { lat:<?php echo $latitude; ?>, lng: <?php echo $longitude; ?> },
            map,
            icon: image,
          });

    <?php 
        } // end while
      } // endif 
     // end marker loop
    ?>

  }

  window.onload = initMap;

</script>

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.