我正在尝试使用其网站https://docs.mapbox.com/mapbox-gl-js/example/geojson-markers/上的示例将自定义标记添加到mapbox地图,但是每次我用我的替换其链接(相同照片格式)或任何链接,如果有人能够向我展示带有自定义照片/标记的工作示例,则没关系,照片不会呈现。我需要使用本示例来工作,我能够以其他方式添加自定义标记,但是我需要使用.addSource和.addLayer的这种特定方式
mapboxgl.accessToken = 'pk.eyJ1IjoibWFya2V0aW5nYnNvIiwiYSI6ImNrYnYwZmk3YjAxZjgyem1wY2Zmc3F4Y2EifQ.gMF-eCCaAHHgWIUoRcnfkg';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v10',
center: [-96, 37.8],
zoom: 3
});
map.on('load', function() {
// Add an image to use as a custom marker
map.loadImage(
'https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png', //here is the problem if i try to replace the image
function(error, image) {
if (error) throw error;
map.addImage('custom-marker', image);
// Add a GeoJSON source with 2 points
map.addSource('points', {
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': [
{
// feature for Mapbox DC
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [
-77.03238901390978,
38.913188059745586
]
},
'properties': {
'title': 'Mapbox DC'
}
},
{
// feature for Mapbox SF
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [-122.414, 37.776]
},
'properties': {
'title': 'Mapbox SF'
}
}
]
}
});
// Add a symbol layer
map.addLayer({
'id': 'points',
'type': 'symbol',
'source': 'points',
'layout': {
'icon-image': 'custom-marker',
// get the title name from the source's "title" property
'text-field': ['get', 'title'],
'text-font': [
'Open Sans Semibold',
'Arial Unicode MS Bold'
],
'text-offset': [0, 1.25],
'text-anchor': 'top'
}
});
}
);
});
根据的文档map.loadImage
,如果要从外部域加载该映像,则该域必须支持CORS(跨源资源共享)。
由于您没有包括要加载的图像,因此无法验证,但似乎与此有关。
编辑:如果需要启用了CORS的服务器上载图像,则可以尝试使用任何可用的图像上载器服务器,例如https://postimg.cc/。但是除了简单的PoC之外,我不会推荐这种方法。
我已经用这张图片尝试过您的代码
并且我就如何为标记添加自定义图像创建了一个小提琴 ...它确实有效,因此可以说代码是正确的,但是您遇到的问题是因为您尝试使用的图像未托管在启用了CORS的域中。
如果此解决方案解决了您的问题,请将其标记为“已接受答案”,这样还可以帮助其他用户了解它是正确的解决方案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句