如何解决无法将点击事件上的传单标记限制为仅关闭一次
因此,我通过 api ajax 调用创建了一个国家/地区 10 个城市的传单标记。当用户单击其中一个城市标记时,会进行不同的 ajax 调用,获取 20 条附近地点的 Wikipedia 文章,并为地图上的每个地点添加一个标记。一切正常,但是如果再次单击城市标记,则会再次进行 ajax 调用,并且每次单击城市标记时都会添加重复的 20 个标记。我想防止多个 ajax 调用/重复标记。
我试过了
.one( "click",function() {//我的代码});
然而结果是以下错误
L.marker(...).bindPopup(...).one 不是函数
我也试过
$(this).off(event);
如有任何帮助,我们将不胜感激,谢谢。
我的js代码:
var largeCityMarker = L.marker(new L.LatLng(cityLat,cityLng),({icon: cityIcon}))
.bindPopup(`<div class="markerContainer"><h3>${cityName}</h3><img class="markerThumbnail" src='${cityThumbnailImg}' onerror="this.style.display='none'"><p class="markerTxtDescription">${cityInfo}</p><div id="city-link"><a href="//${cityUrl}" target="_blank">${cityText}</a></div></div>`,cityOptions)
.on('click',function() {
$.ajax({
url: "assets/php/wikiLoops.php",type: 'GET',dataType: 'json',data: {
lat: this.getLatLng().lat,lng: this.getLatLng().lng,countryCodeA2: borderCountryCode
},success: function(result) {
//wiki Find Nearby Places for cities
wikiCluster = new L.markerClusterGroup();
console.log(result);
result.data.wikiCitiesData.geonames.forEach(place => {
var wikiPlaceIcon = L.icon({
iconUrl: 'assets/img/icons/wikipedia.png',iconSize: [50,50],// size of the icon
popupAnchor: [0,-15]
});
var customOptions =
{
'maxWidth': '300','className' : 'custom'
};
wikiPlaceName = place.title;
wikiPlaceLat = place.lat;
wikiPlaceLng = place.lng;
wikiSummary = place.summary;
wikiUrl = place.wikipediaUrl;
wikiThumbnail = place.thumbnailImg;
var customPopup = `<div class="card" style="width: 18rem;">
<div class="card-body"><h5 class="card-title">${wikiPlaceName}</h5><img class="img-thumbnail float-right" style="max-width: 100px" src="${wikiThumbnail}" onerror="this.style.display='none'"><p class="card-text" id="wiki-sum">${wikiSummary}</p><a href="//${wikiUrl}" target="_blank"class="card-link">Read more</a><a href="#" class="card-link"></a></div></div>`;
wikiPlaceMarker = L.marker(new L.LatLng(wikiPlaceLat,wikiPlaceLng),({icon: wikiPlaceIcon})).bindPopup(customPopup,customOptions);
console.log(wikiPlaceMarker);
capCityCluster.addLayer(wikiPlaceMarker);
});
},error: function(jqXHR,textStatus,errorThrown) {
console.log("wikiLoopPHP",errorThrown);
}
});
});
largeCityCluster.addLayer(largeCityMarker);
});
});
}
},
解决方法
看起来您将 jQuery 语法与 Leaflet 语法混淆了。
在 Leaflet 中,使用 once
method 附加一个应该只触发一次然后自动删除的事件侦听器:
表现为 on(…)
,除了监听器只会被触发一次然后被移除。
L.marker(latLng)
.bindPopup(popupContent)
.once('click',function() {});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。