How can i display the data button in the table that i created using javascript?

I’m trying to create a table that displays the selected data from the json file. With the coordinates data selected from the json file, i need to make the coodinates data into a button so i can setZoom() to the map when the corresponded coordinated is clicked. I am able to make the button work when is not in the table. but now i am struggling to make it work in the table. I have no idea how to make it work. Please help me it will be a very big help to me. Thanks :slight_smile:

here is my html code:

<div class="col-12 form-group mt-5">
      <div class="card" style="box-shadow: 0 0 8px rgb(0, 0, 0, 0.3)">
        <h6 class="text-muted text-center p-3 mt-2">Map</h6>
        <div class="card-body">
          <div id="googleMap" style="width: 100%; height: 400px"></div>
        </div>
      </div>
    </div>
    <div id="numbers" class="data_btn"></div>

    <div class="container">
      <div class="table-responsive">
        <table class="table table-bordered table-stripped" id="events_table">
          <thead>
            <tr>
              <th>ROBOT ID</th>
              <th>PS</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
    </div>

here is my js code:

<script>
      function myMap() {
        var mapProp = {
          position: new google.maps.LatLng(32.735316, -117.149046),
          zoom: 1,
        };
        var map = new google.maps.Map(
          document.getElementById("googleMap"),
          mapProp
        );
      }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY=myMap"></script>

<script>
      $.getJSON("example.json", function (data) {
        const map = new google.maps.Map(document.getElementById("googleMap"), {
          zoom: 5,
          center: new google.maps.LatLng(
            1.5298600000000002,
            110.36003000000001
          ),
          mapTypeId: google.maps.MapTypeId.ROADMAP,
        });
        var output = "";
        const { tracks } = data;
        $.each(tracks, function (key, value) {
          const NewlatLngStr = value.ps.split(",");
          const results = document.getElementById("numbers");
          function ZoomAndCenter(NewlatLngStr) {
            map.setCenter(
              new google.maps.LatLng(NewlatLngStr[0], NewlatLngStr[1])
            );
            map.setZoom(20);
          }
          const btn = document.createElement("button");
          const Questions = NewlatLngStr;
          btn.textContent = NewlatLngStr;

          btn.addEventListener("click", () => ZoomAndCenter(Questions));
          results.appendChild(btn);
          console.log(btn);

          output += "<tbody>";
          output += "<tr>";
          output += "<td>" + value.Robotid + "</td>";    
          output += "<td>" + btn + "</td>";
          output += "</tr>";
          output += "</tbody>";
        });

        $("#events_table").html(output);

      });
    </script>

here is how my json file data look like

{
  "result": 0,
  "location": {
    "walk": null
  },
  "tracks": [
    { "Robotid": "123456789", "ps": "1.5298600000000002,110.36003000000001" },
    { "Robotid": "123456789", "ps": "1.52872, 110.36453" },
    { "Robotid": "123456789", "ps": "1.5278, 110.36775000000002" },
    { "Robotid": "123456789", "ps": "1.5273500000000002, 110.37160000000002" }
  ]
}

You cannot add the event listener before you have added the button to the DOM. Switch the two rows and append the button to the DOM before you add the event listener.

I had to check, you can add an eventlistener to an element before appending it to the DOM.

Two thing that standout to me.

Script order. Shouldn’t this be the first script? I could be wrong.

<script src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY=myMap"></script>

Two

const NewlatLngStr = value.ps.split(","); // creates an Array
...
const Questions = NewlatLngStr; // should be lowercase. Are they questions?
btn.textContent = NewlatLngStr; // assigning an array as text content.

Split creates an Array. You are assigning an array as textContent.

As far as I know only if you use event delegation. But I might be wrong

Event delegation is certainly one option, but yes you can. :slight_smile:
https://codepen.io/rpg2019/pen/Yzvdqze

edit: looking through the code, this isn’t going to work though

 output += "<td>" + btn + "</td>";
1 Like

Without having a working example, this is only guess work.

First of all I have moved some of the code out into separate functions. Ideally you want to keep functions short. It makes them more manageable.

const getMap = function() {
  return new google.maps.Map(document.getElementById("googleMap"), {
    zoom: 5,
    center: new google.maps.LatLng(
     1.5298600000000002,
     110.36003000000001
    ),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
  });
}

const ZoomandCenter = function (newLatLng) {
  const map = getMap();
	
  map.setCenter(
    new google.maps.LatLng(newLatLng[0], newLatLng[1])
  );
  map.setZoom(20);
}

const createTbody = function (Robotid, buttonText) {
  const tbody = document.createElement('tbody')
		
  tbody.insertAdjacentHTML('afterbegin', `
    <tr>
      <td>${Robotid}</td>
      <td><button class='btn'>${buttonText}</button></td>
    </tr>
  `)

  return tbody
}


$.getJSON("example.json", function (data) {
  const { tracks } = data;
	
  tracks.forEach((track) => {
    const {Robotid, ps} = track
    const newLatLng = ps.split(',') // array
    const tbody = createTbody(Robotid, 'Button Text')
	
    // can query the newly created element
    const btn = tbody.querySelector('.btn')
    // and add an eventListener
    btn.addEventListener('click', () => ZoomAndCenter(newLatLng))
	
    // do something with tbody ? e.g. append it?
  })
}

The above is not a working solution, but hopefully some ideas in the right direction.