Marker(s) Not Showing on Leaflet Map - Twig Location Array to Leaflet Map

345 views Asked by At

I have a template here with my twig/javascript - I am having an issue passing "locations" through my javascript function which is to grab the latitude and longitude coordinates from the array and pass that through to display the map marker(s) on the map which currently do not show up on the map.

Right now, I have no errors and the coordinates are being pulled correctly via Twig and are logging appropriately to the console via

console.log(locations) in my script after defining the locations variable:

var locations = {{ coords|json_encode|raw }};

which outputs in the console as

> {lat: "50.41830281867368", lng: "-104.51004534959793"}
    lat: "50.41830281867368"
    lng: "-104.51004534959793"
    > __proto__: Object

and it also displays the correct coordinates when using

{{ dump(coords) }}

my current code in its entirety (HTML/Twig & Scripts) below:

  <body>
    {% include '_includes/nav' %}
    <div>
      {% block content %}

      {% endblock %}
      <div class="map-test">
        {% set entries = craft.entries().section('showHomes').all() %}
        {% set coords = {} %}
        {% for post in entries %}
          {% for coord in post.lotInfo %}
            {% if coord.createNewEntry == '1' %}
              {% set coords =
                coords|merge({
                  lat: coord.latitude,
                  lng: coord.longitude
                })
              %}
            {% endif %}
          {% endfor %}
        {% endfor %}
      </div>
    </div>
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
      integrity="sha512QVftwZFqvtRNi0ZyCtsznlKSWOStnDORoefr1enyq5mVL4tmKB3S/EnC3rRJcxCPavG10IcrVGSmPh6Qw5lwrg=="
      crossorigin=""></script>
    <script>
      var map = L.map('map', { scrollWheelZoom: false }).setView( [50.4205,-104.52], 15, )
      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 19, 
      minZoom: 14.5 }).addTo(map)

      var locations = {{ coords|json_encode|raw }};

      function addToMap(locationArray) { 
        [].forEach.call(locationArray, function(location) { 
          var marker = L.marker([{lat:locations.lat,lng:locations.lng}]).addTo(map); 
          }); 
        }
      addToMap(locations); 
      console.log(locations);
    </script>
  </body>

So basically everything seems to be working- no errors and the coordinates are outputting in the console when logged, it's just that my javascript function does not seem to be adding the markers to the map which leads me to believe the problem is somewhere with that function and its ability to interpret

var marker = L.marker([locations.lat, locations.lng]).addTo(map);

I have also tried this variation on the variable marker:

var marker = L.marker([{lat:locations.lat,lng:locations.lng}]).addTo(map); 

Any thoughts or suggestions are appreciated, thank you.

0

There are 0 answers