单击外部链接时更改谷歌地图标记图标

Change google maps marker icon when external link is clicked?

本文关键字:图标 谷歌 地图 外部 链接 单击      更新时间:2023-09-26

我有一个谷歌地图,上面有很多标记(从MySQL数据库中收集)。我目前正在使用以下代码在单击标记时更改标记的图标:

var redbikeicon = "images/bike_red.png";
<?php
    $result=mysql_query("select * from sites") or die(mysql_error());
    while($row=mysql_fetch_assoc($result)){
        ?>
        marker = new google.maps.Marker({
        position: new google.maps.LatLng(<?php echo $row['Latitude']; ?>, <?php echo $row['Longitude']; ?>),
        map: map, icon: bikeicon});
        //add event to every marker
        google.maps.event.addListener(marker, 'click', function(){
            //change icon color
            this.setIcon(redbikeicon);      //replace default icon with red version (color-marking all chosen markers)
        })
        <?php
    }
    ?>

这段代码工作正常,但是我现在需要在单击页面上的链接时发生同样的事情 - 地图旁边的页面上有一个链接列表,每个链接对应于地图上的一个标记。单击链接时,相应的标记应更改颜色,就像单击标记本身时一样。我该如何实现此目的?

我做了类似的事情,除了我使用悬停。我在下面为您更改了它。我也使用jQuery。无论如何,您设置单击链接上的事件。该链接具有一个名为"record_id"的属性,该属性对应于您为标记设置的属性,也称为"record_id"。

单击链接时,获取 id,然后遍历所有标记,直到找到匹配的标记,然后使用 googlemaps api 中提供的 setIcon 方法更改图标。

希望有帮助。

设置 ID:

marker = new google.maps.Marker({
    record_id: record_id,
    position: point,
    map: map,
    title: name,
    icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=whatever|BDD73C|000000'
});

在定位点上设置操作:

$("a.whatever").click(function(){
    var id = $(this).attr('id');
    changeMarker(id);                             
});

使用 setIcon 将图标交换为不同的颜色之一:

function changeMarker(record_id){
    for (i in Markers){
        if(Markers[i].record_id == record_id){
            Markers[i].setIcon('http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=title|EC2A8C|000000');
        }
    }
}

单击链接时触发标记上的"单击"事件。

google.maps.event.trigger(gmarkers[i], "click");

具有可单击的动态侧边栏的示例(单击侦听器打开信息窗口)