You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在L.geoJSON的pointToLayer中实例化Marker报错的解决方案咨询

修复 Leaflet 标记不显示及 this.callInitHooks is not a function 错误

嘿,我一眼就看到了代码里的两个关键问题,正是它们导致了你遇到的报错和标记不显示的情况,咱们来逐个修复:

问题1:Marker 初始化方式错误

你当前在pointToLayer里创建标记的写法不对,Leaflet要求标记的配置项(比如自定义图标)需要放在一个配置对象中,而不是直接把图标对象传进去。原来的写法会让Leaflet误把图标对象当成标记的初始化配置,进而触发this.callInitHooks is not a function这个内部错误。

错误写法:

return L.Marker(latlng, geojsonMarkerOptions);

正确写法:

return L.marker(latlng, { icon: geojsonMarkerOptions });

问题2:变量名不匹配

你定义的GeoJSON图层变量是howdy,但后续加载数据和添加到地图时却用了未定义的Shelter变量,这会导致数据根本没被添加到图层里,地图自然看不到任何标记。

需要把所有Shelter的引用改成howdy。


修复后的完整代码

var map = L.map('map', { 
    center: [53.423933, -7.94069], 
    zoom: 7, 
    layers: [grayscale] 
}); 
var url = "howdy.json"; 
var geojsonMarkerOptions = L.icon({ 
    iconUrl: 'howdy.png', 
    iconSize: [16, 28], 
    iconAnchor: [8, 18], 
    popupAnchor: [-3, -13] 
}); 

function forEachFeature(feature, layer) { 
    var popupContent = feature.properties.Cabin + feature.properties.Crew + feature.properties.Mobile; 
    if (feature.properties && feature.properties.popupContent) { 
        popupContent += feature.properties.popupContent; 
    } 
    layer.bindPopup(popupContent); 
}; 

var howdy = L.geoJSON(null, { 
    onEachFeature: forEachFeature, 
    pointToLayer: function (feature, latlng) { 
        return L.marker(latlng, { icon: geojsonMarkerOptions }); 
    } 
}); 

$.getJSON(url, function(data) { 
    howdy.addData(data); 
}); 
howdy.addTo(map); 

这样修改后,首先纠正了标记的初始化逻辑,解决了报错问题;其次修正了变量名,确保GeoJSON数据能正确加载到图层并显示在地图上。

内容的提问来源于stack exchange,提问作者NightCrawler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:37:33