使用自定义标记更改Leaflet默认标记

3
我需要寻求关于如何将Leaflet默认标记(蓝色标记)更改为自定义标记的建议/帮助。我在StackOverFlow上搜索到了一些方法,但似乎无法使它们中的任何一种起作用。最接近成功的是,我能够在我的地图上添加一个新图标,但无法将默认图标更改为我的自定义图标。我正在使用leaflet omnivore,因为我喜欢使用csv文件,所以这种方法非常适合我。另外,我是一个大D3用户,我正在尝试学习一些新技能。以下是我正在使用的代码。然而,我的终极目标是用不同的标记/图标(像svg、png、jpg或gif等文件类型)替换默认的蓝色标记,就像我可以通过D3实现的那样。感谢您的帮助,提前致谢。
omnivore.csv('data/pointData5.csv')
.on('ready', function(layer) {

/*Couldn't get this to work*/
var tankIcon = L.icon({
iconUrl: 'graphic/tank.png',
iconSize: [50,40]
}); 
L.geoJson(layer,{
pointToLayer: function(feature,latlng){
  return L.marker(latlng,{icon: ratIcon});
}
}).addTo(map);

/*Only place one icon on the map and changing all the default markers*/
var markers = new L.LayerGroup();   
var myIcon = L.icon({ 
    iconUrl: 'graphic/tank.png',
    iconSize: [20, 20],
    iconAnchor: [22, 94],
    popupAnchor: [-3, -76],
    shadowSize: [68, 95],
    shadowAnchor: [22, 94]
});

marker = L.marker([50.505, 30.57], {icon: myIcon}).bindPopup("Hi there").addTo(markers);
map.addLayer(markers);

/*This code works perfect - providing me what I was hoping for*/
        this.eachLayer(function(marker) {
        marker.bindPopup(marker.toGeoJSON().properties.imageTitle + ', ' + "<br />" + marker.toGeoJSON().properties.discrip + ', ' + "<br /><a class='fancybox-thumb'   rel='fancybox-button'  rel='fancybox-thumb' data-fancybox-group='gallery' href='graphic/" + marker.toGeoJSON().properties.popup +"'><img src='graphic/" + marker.toGeoJSON().properties.popup + "' style='width:100%' /></a>");
    });
})
.addTo(map); 

关于读取与您的 Leaflet 标记相关联的 GeoJSON 数据,您可以简单地使用 marker.feature.properties 而不是调用 marker.toGeoJSON() 方法,后者在底层执行更多操作。 - ghybs
1个回答

2

我做了更多的研究,找到了如何使用 omnivore Leaflet/Mapbox 添加自定义标记到我的地图的答案。如果有人需要这么做,以下脚本对我有效。

//set up a customized icon to use for the point data
var customIcon = L.icon({
iconUrl: 'graphic/tank.png',
iconSize: [18, 9], //size of the icon in pixels
iconAnchor: [9, 9], //point of the icon which will correspond to marker's
location (the center)
popupAnchor: [0, 0] //point from which the popup should open relative to 
the iconAnchor
});


omnivore.csv('data/pointData5.csv')
.on('ready', function(layer) {
    this.eachLayer(function(marker) {
         //change the icons for each point on the map
        marker.setIcon(customIcon);
         //create popup with text and image - click image in popup, large  
image displays in fancybox
        var popupText =
             marker.bindPopup(marker.toGeoJSON().properties.imageTitle +
 ', ' + "<br />" + marker.toGeoJSON().properties.discrip + ', ' + "<br
 /><a class='fancybox-thumb'    rel='fancybox-button'  rel='fancybox-
thumb' data-fancybox-group='gallery' href='graphic/" + 
marker.toGeoJSON().properties.popup +"'><img src='graphic/" + 
marker.toGeoJSON().properties.popup + "' style='width:100%' /></a>");
});
}).addTo(map);      

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接