我正在尝试通过表格行单击来定位谷歌地图



在我的网页上,当页面加载时,它加载了一个由我的数据库内容生成的表格,所有的标记都立即加载到地图上,但我想能够点击表格行到中心并缩放它所代表的标记,我试图弄清楚,但我是新手JQuery/Javascript只是一种学习我去。

这是我的JQuery函数我正在工作…

$("table#listOfStops").find('tr').each(function() {
  $(this).on('click', function() {
      alert(arrMarkers.length);
      var num = $(this).data("num");
      for (var i = 0; i < arrMarkers.length; i++) {
        if ( arrMarkers.id == 'marker'+num) {
          map.setCenter(arrMarkers[i].position);
          map
        }
      }
  });
});

这是我的表:

  <table id="listOfStops" class="table table-striped">
  <thead>
  <tr>
    <th>Stop #</th>
    <th>Street Name</th>
  </tr>
  </thead>
  <tbody>
  <?php
  $i = 0;
  while($stmt -> fetch()) {
    echo '<tr  id="' . $i . '">';
    echo '<td>' . $gStopNumber . '</td>';
    echo '<td>' . $gStreetName . '</td>';
    echo '</tr>';
  $i++;} $stmt -> close(); $mysqli -> close(); ?>  
  </tbody>
  </table>

在页面加载时,它会加载这个初始化函数:

function initialize() {
  geocode = new google.maps.Geocoder();
 var mapOptions = {
  zoom: 10,
  center: new google.maps.LatLng(56.7626362, -111.379652),
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  disableDefaultUI: false,
  zoomControl: true,
  zoomControlOptions: {
    style: google.maps.ZoomControlStyle.LARGE
  }
};
  map = new google.maps.Map(document.getElementById('gmaps'),
  mapOptions);
  google.maps.event.addListener(map, 'click', function(event) {
    var latitude = event.latLng.lat();
    var longitude = event.latLng.lng();
    deleteOverlays();
    addMarker(event.latLng);
    updateTextFields(latitude, longitude);
  });
  <?php while($stmt -> fetch()) { ?>
  var long = "<?php echo $gLongitude ?>";
  var lati = "<?php echo $gLatitude; ?>";
  var title = "<?php echo $gTitle; ?>"
  setMarker(lati, long, title);
  <?php } $stmt -> close(); $mysqli -> close();?>

}

,然后将每个标记设置为映射,并使用setMarker函数将它们压入数组:

function setMarker(lat,lon, markerTitle) {
  var latLonMarker = new google.maps.LatLng(lat,lon);
  marker = new google.maps.Marker({
    position: latLonMarker,
    map: map,
    icon: 'icon.png',
    title: markerTitle
  });
  google.maps.event.addListener(marker, 'dragend', function() {
    $('#inputLatitude').val(this.getPosition().lat());
    $('#inputLongitude').val(this.getPosition().lng());
  });
  arrMarkers.push(marker);
}

我只是很难将表行与标记数组中的适当标记点匹配以设置位置,例如map.setPosition(arrMarkers[i]);

jquery。每个函数提供每个结果的索引。如果您将查询修改为.find('tbody tr'),则索引应该与数组中的位置匹配比如:

$("table#listOfStops").find('tbody tr').each(function(idx) {
  var rowNumber=idx;
  $(this).on('click', function() {  
        map.setCenter(arrMarkers[rowNumber].getPosition());
  });
});

最新更新