[英]Creating custom markers with Leaflet.js add multiple markers on the map
我正在编写一个应用程序,并尝试使用Leaflet.js添加自定义标记。到目前为止,该代码有效,并且已成功将自定义标记添加到地图,但是默认标记也存在于地图上。
var mymap = L.map('mapid').setView([-1.3938636,36.7442377], 13);
var mapdata = $.ajax({
url: '/data.json',
dataType: 'text',
success: function(data) {
var geojson;
geojson = $.parseJSON(data);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
maxZoom: 18,
id: 'mapbox.streets',
accessToken: 'ACCESS_TOKEN'
}).addTo(mymap);
//add external geojson to map
var cordinates = L.geoJSON(geojson).addTo(mymap);
//Add popups to markers
function onEachFeature(feature,layer){
if (feature.properties && feature.properties.popupContent) {
layer.bindPopup(feature.properties.popupContent);
}
}
L.geoJSON(geojson, { onEachFeature: onEachFeature }).addTo(mymap);
//Adding custom markers to maps
var HospIcon = L.icon({
iconUrl: '<%= asset_path('red_MarkerH.png') %>',
iconSize: [20, 50], // size of the icon
shadowSize: [50, 64], // size of the shadow
iconAnchor: [22, 94], // point of the icon which will correspond to markers location
shadowAnchor: [4, 62], // the same for the shadow
popupAnchor: [-3, -76] // point from which the popup should open relative to the iconAnchor
});
var Custom_marker = L.geoJSON(geojson, {
pointToLayer : function(feature,latlng){
return L.marker(latlng, {icon: HospIcon}).addTo(mymap);
}
});
}
});
var popup = L.popup();
function onMapClick(e) {
popup
.setLatLng(e.latlng)
.setContent("You clicked the map at " + e.latlng.toString())
.openOn(mymap);
}
mymap.on('click', onMapClick);
我该如何解决。任何帮助将不胜感激。 这是地图的样子,蓝色标记是默认标记,红色标记是自定义标记
非常感谢您的任何帮助,谢谢。
因为这个功能
var cordinates = L.geoJSON(geojson).addTo(mymap);
将添加您的坐标并使用默认标记图标,如果要修改默认标记,则应在该函数中定义回调,如下所示
my_json = L.geoJson(geojson, {
pointToLayer: function (feature, latlng) {
var smallIcon = new L.Icon({
iconSize: [27, 27],
iconAnchor: [13, 27],
popupAnchor: [1, -24],
iconUrl: 'icone/chapel-2.png'
});
return L.marker(latlng, {icon: smallIcon});
}
});
在您的情况下,标记绘制了两次,因为您从第一次注入GeoJson开始就两次渲染了两次addTo(mymap)
。 其次,当您定义图标并将其添加到地图时
参考资料:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.