javascript - 当您有多个标记时,更改单击的标记图标
问题描述
我试图在单击标记时更改标记图标问题是下面的代码仅更改我添加到地图的最后一个标记而不是我单击的标记,因此如果我只有一个标记它会正常工作。我尝试查找它,但我能找到的所有示例仅适用于地图中加载的 1 个标记。我尝试了两种不同的侦听器方式,第二种方式在第一种方式下方被注释掉,两者都只是更改最后加载的标记的图标。
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 95%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 95%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&callback=initMap"
async defer></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://unpkg.com/@google/markerclustererplus@4.0.1/dist/markerclustererplus.min.js"></script>
<script>
let markers = [];
let map;
function loadMarkers(ssStr)
{
$.getJSON(ssStr, function(data) {
for (var i = 0; i < data.feed.entry.length; i++)
{
var latLng = new google.maps.LatLng(data.feed.entry[i]['gsx$lat']['$t'],
data.feed.entry[i]['gsx$long']['$t']);
var marker = new google.maps.Marker({
position: latLng,
map: map,
label:data.feed.entry[i]['gsx$structure']['$t'],
icon: { url: "http://maps.google.com/mapfiles/ms/icons/red.png" }
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
//Change the marker icon
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green.png');
});
/* marker.addListener("click", (event) => {
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green.png');
}); */
}
var latLng = new google.maps.LatLng(data.feed.entry[0]['gsx$lat']['$t'],
data.feed.entry[0]['gsx$long']['$t']);
map.setCenter(latLng);
});
}
function initMap() {
console.log("initMap");
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(41.5, -72)
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
loadMarkers("http://spreadsheets.google.com/feeds/list/SSID/od6/public/values?alt=json");
}
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>
解决方案
推荐阅读
- javascript - 用于切换按钮颜色的 JavaScript
- azure - 如何使用 ARM 模板创建 Azure Kubernetes 服务 (AKS)
- node.js - 如何使用 node.js 将数组存储到 sqlite
- python - pandas get difference of 2 times assuming if end_time is lower than start_time it is the next day
- javascript - 节点红色多个值到 influxDB
- regex - 正则表达式具有三分之二的字符类型
- c# - 从一个时期中选择一天 - 重复
- php-carbon - 现在()是 10 月 31 日。Carbon认为下个月是12月。有人可以告诉我为什么会这样吗?
- batch-file - 批处理文件将日期添加到文件名
- c# - C# net core 巧妙地简化 Lambda 表达式 - 更新