javascript - 如何根据位置列表从 map 中删除标记?

标签 javascript php jquery html google-maps

在这个页面中,我在顶部有一个表格,其中包含社区名称,在该表格下方我有一个谷歌地图,显示了放置的这些社区名称的标记位置。现在我要做的是,当我单击表行中的删除按钮(即通过 PHP 函数 delete_btn())时,我需要删除与表行对应的特定标记删除 map 中的按钮位置。我怎样才能做到这一点?

我已经在下面发布了我的代码结构:

<div>
    <table id="sum_table">
        <tr class="titlerow">
            <th>S.N.</th>
            <th>Community</th>
            <th width="18%">Action</th>
        </tr>
        <? 
        $sn = 1;
        while($result= mysql_fetch_row($res))
        {
            ?>
            <tr id="<?php echo $result[0];?>">
                <td align="center"><? echo $sn++; ?></td>
                <td align="center"><? echo $result[1] ?></td>
                <td>
                    <?php echo delete_btn("delete.php?id=", $result[0]); ?>
                </td>                       
            </tr>
            <?
        }
        ?>
    </table>
</div

<?php
$query="SELECT com_name,com_lat,com_lon FROM community where mun_id=10";
$result=mysql_query($query);
?>

<script type="text/javascript">
    var beaches = [
    <?php
    $i=0;
    if ($num>0){
        while ($r=mysql_fetch_array($result))   {
            ++$i;
            $i != $num ? $k=',' : $k='';
            ?>
            ['<?php echo $r['com_name'];?>',<?php echo $r['com_lat'];?>, <?php echo $r['com_lon'];?>]<?php echo $k?>
            <?php   }  }  ?>
            ];

            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 8,
                center: new google.maps.LatLng( beaches[0][1], beaches[0][2]),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });
            var infowindow = new google.maps.InfoWindow();
            var marker, i;
            var com_Image = {
                url: 'assets/img/icon/pin-single-1.png',
                size: new google.maps.Size(61, 72),
                origin: new google.maps.Point(0, 0),
                anchor: new google.maps.Point(0, 16)
            };
            var shape = {
                coords: [1, 1, 1, 20, 18, 20, 18, 1],
                type: 'poly'
            };

            for (i = 0; i < beaches.length; i++) {
                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(beaches[i][1], beaches[i][2]),
                    icon: com_Image,
                    map: map
                });
                google.maps.event.addListener(marker, 'click', (function(marker, i) {
                    return function() {
                        infowindow.setContent(beaches[i][0]);
                        infowindow.open(map, marker);
                    }
                })(marker, i));
            }

        </script>

最佳答案

在标记上使用 .setMap() 函数将其从 map 中移除:

To remove a marker from the map, call the setMap() method passing null as the argument.1

marker.setMap(null);

Note that the above method does not delete the marker. It simply removes the marker from the map. If instead you wish to delete the marker, you should remove it from the map, and then set the marker itself to null.

为了让表格中的操作链接能够删除项目,我们需要让删除链接的 id 参数对应于 JavaScript 代码中标记列表中的项目。

<div>
<table id="sum_table">
    <tr class="titlerow">
        <th>S.N.</th>
        <th>Community</th>
        <th width="18%">Action</th>
    </tr>
    <?php
    $query="SELECT com_id, com_name,com_lat,com_lon FROM community where mun_id=10";
    $result=mysql_query($query);
    $sn = 1;
    $beaches = array();
    while($result= mysql_fetch_row($res))
    {
        //assuming 1 => com_name, 2 => com_lat, 3 => com_lon
        //assuming so, you should be able to do this instead: 
        //$beaches[] = array($result['com_name'], $result['com_lat'], $result['com_lon']);

        $beaches[] = array($result[1], $result[2], $result[3]);
        ?>
        <tr id="<?php echo $result[0];?>">
            <td align="center"><? echo $sn++; ?></td>
            <td align="center"><? echo $result[1] ?></td>
            <td>
                <button class="deleteMarker" data-id="delete_<?php echo ($sn - 1)); ?>">Remove</button>
            </td>                       
        </tr>
        <?
    }

    ?>
</table>

然后使用 $beaches 数组在 Javascript 中创建标记列表,并在点击处理程序中检查类名(例如 deleteMarker ) 使用 String.indexOf() .如果单击的元素具有该类,则使用 the data attributesdata-id 属性中获取要删除的索引。

<script type="text/javascript">
var beaches = <?php echo json_encode($beaches); ?>;

function clickHandlerDelegate(clickEvent) {
  if (clickEvent.target.className.indexOf('deleteMarker') > -1) {
    var index = clickEvent.target.dataset.id;
    markers[index].setMap(null);
  }
}
//rest of javascript - e.g. for creating map
</script>

参见下面示例中的演示(特别是在函数 clickHandlerDelegate() 中,它使用 addEventListener() 连接到点击事件)。

var beaches = [
  ["Haringhata", 21.984606, 89.974250],
  ["West Bengal, India",
    21.681855, 88.584980
  ]
];
var markers = [];
var map; //set scope here so various functions can use them

function clickHandlerDelegate(clickEvent) {
  if (clickEvent.target.className.indexOf('deleteMarker') > -1) {
    var index = clickEvent.target.dataset.id;
    markers[index].setMap(null);
  }
}

function initialize() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8,
    center: new google.maps.LatLng(beaches[0][1], beaches[0][2]),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  var infowindow = new google.maps.InfoWindow();
  var marker, i;
  var shape = {
    coords: [1, 1, 1, 20, 18, 20, 18, 1],
    type: 'poly'
  };

  for (i = 0; i < beaches.length; i++) {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(beaches[i][1], beaches[i][2]),
      map: map
    });
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
      return function() {
        infowindow.setContent(beaches[i][0]);
        infowindow.open(map, marker);
      }
    })(marker, i));
    markers.push(marker);
  }

}
google.maps.event.addDomListener(window, "load", initialize);
//set up delegate
document.addEventListener('DOMContentLoaded', function() {
  document.addEventListener('click', clickHandlerDelegate);
});
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<table id="sum_table">
        <tr class="titlerow">
            <th>S.N.</th>
            <th>Community</th>
            <th width="18%">Action</th>
        </tr>
        <tr>
        <td>1</td>
         <td>Haringhata</td>
         <td><button class="deleteMarker" data-id="0">Remove</button></td></tr>
        <tr>
        <td>2</td>
         <td>West Bengal, India</td>
         <td><button class="deleteMarker" data-id="1">Remove</button></td></tr>
         </table>
<div id="map"></div>


1 https://developers.google.com/maps/documentation/javascript/markers#remove

关于javascript - 如何根据位置列表从 map 中删除标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42546214/

相关文章:

javascript - 找到div并改变颜色

javascript - Controller 中的 Angular 函数在 promise 后没有被调用

javascript - 在 ul 列表中添加 div 元素

javascript - jquery 检查是否以链接开头

php - 即使我没有更改任何内容,也要更新 TIMESTAMP 列?

php - 为什么人们不使用序号来存储图像?

php - 如何从网络代码 (php) 运行 apktool

javascript - Bootstrap Alpha 4 导航栏点击不起作用

javascript - array.prototype.slice.call 中的原型(prototype)有什么用

javascript - *ngFor 使用异步管道进行本地分配并减少订阅数量