Leaflet中使用L.geoJSON加载点数据时如何自定义图标?
解决方法
L.geoJSON 不支持直接在配置项里传 icon 参数生效,需要通过内置的 pointToLayer 回调指定点要素的渲染规则。
你只需要将原代码中 L.geoJSON 相关的写法替换为如下内容即可:
L.geoJSON(geojson, { // 针对点类型要素的渲染回调 pointToLayer: function (feature, latlng) { // 返回指定了自定义图标的Marker实例 return L.marker(latlng, { icon: icons }); } }).addTo(mymap);
完整可运行代码示例
JS 部分
const geojson = { "name": "interseccao_circulo", "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": {}, "geometry": { "type": "MultiPoint", "coordinates": [ [-46.62831244066412, -23.551014464955063] ] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "MultiPoint", "coordinates": [ [-46.63242614612176, -23.55277865770234] ] } } ] } var mymap = L.map('mapdiv', { center:[-23.552778, -46.632426], zoom:16, maxZoom:20, zoomControl:false, attributionControl:false }); var lyrOSRHOT = L.tileLayer.provider('OpenStreetMap.HOT'); mymap.addLayer(lyrOSRHOT); var icons = new L.Icon({ iconUrl: "https://i.imgur.com/ZcGeIVz.png", iconSize: [40, 40], }); // 修改后的geoJSON渲染代码 L.geoJSON(geojson, { pointToLayer: function (feature, latlng) { return L.marker(latlng, { icon: icons }); } }).addTo(mymap);
HTML 部分
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet-src.min.js" integrity="sha512-XQr+/1RXvYozXiwrumwtu3lqQmVwZ8nkLUrC/mc3HBHw4Imh++RXjwtLQFuOz3i65j9CSfKt50x6w/uUY2ovOQ==" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-providers/1.12.0/leaflet-providers.min.js" integrity="sha512-LixflAm9c0/qONbz9F1Ept+QJ6QBpb7wUlPuyv1EHloTVgwSK8j3yMV3elnElGQcv7Y5QTFlF/FqyeE/N4LnKQ==" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="anonymous" /> <div id="mapdiv" style="height:100vh; width: 100vw"></div>
拓展说明
如果需要根据不同要素的属性显示不同的图标,可以在pointToLayer回调中读取feature.properties字段做判断,返回不同的L.Icon实例即可。
内容的提问来源于stack exchange,提问作者raylight
相关产品推荐
相关产品推荐

