Pressing a button that directs me to a certain position, reverse geocoding?

  google-maps, javascript, php

I’m new to programming and new to the page, so I still don’t understand the rules well.

I generated buttons with 10 addresses from the database, use a geocoder to show them on the map when pressing the button it shows me the address in order of id with its respective button, it worked fine,
then I tried using the reverse geocoding that when pressing the button directs me to the position of the address but now using latitude and longitude. I will attach the code to see if anyone understands and can help me understand my mistake.


  const geocoder = new google.maps.Geocoder();
  var btnes = document.getElementsByClassName('address');
  for (var i = 0; i < btnes.length; i++) {
    btnes[i].addEventListener('click', function() {
      

      geocodeLatLng(geocoder, map);

    });
  };
  

function geocodeLatLng(geocoder, map) {
  const input = document.getElementById("latlng").value;


  const latlngStr = input.split(",", 2);
  const latlng = {
    lat: parseFloat(latlngStr[0]),
    lng: parseFloat(latlngStr[1])
  }
 
  
  
  geocoder.geocode({ location : latlng }, (results, status) => {
    if (status === "OK") {
      if (results[0]) {
        const icono = {
        url: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png",
        scaledSize: new google.maps.Size(40, 40), // scaled size
        origin: new google.maps.Point(0,0), // origin
        anchor: new google.maps.Point(27, 64), // anchor
        size: new google.maps.Size(250,250)
      };
        map.setZoom(12);
        marker2 = new google.maps.Marker({
          position: latlng,
          icon: icono,
          map: map
        });
      } else {
        window.alert("No results found");
      }
    } else {
      window.alert("Geocoder failed due to: " + status);
    }
  });

  
 
}
 <div id="container-right"  >
          
                $query2 = mysqli_query($link,"SELECT * FROM suscriptor WHERE estado = '0' ")
or die(mysqli_error());
                  while($row2 = mysqli_fetch_array($query2))
                  {
                  $lat2 = $row2['lat'];
                  $lon2 = $row2['lng'];
                  $direccion = $row2['direccion'];
                  echo("<input type='submit' class='address' id='btnDir' onclick='clear2()' value='$direccion'/>
 <input id='latlng' type='hidden' value='$lat2,$lon2' />
                  
                  <br> n");
                  
                }
                 
                ?>
            
          </div>

The code shows me that when I press the buttons, they all show me the first position and not as I expected for example button 2 with position 2.

I used a hidden to go passing the latitude and longitude of the Database.

Since in geocoder this way it worked for me but the difference is that I did it with the address.
Where is my mistake?

Source: Ask Javascript Questions

LEAVE A COMMENT