mapbox - mapbox gl js中的自定义标记不起作用?
问题描述
我正在尝试使用他们网站https://docs.mapbox.com/mapbox-gl-js/example/geojson-markers/中的示例将自定义标记添加到地图框地图,但每次我用我的链接替换他们的链接(相同照片格式)或任何链接,没关系,照片不会呈现,如果有人能够向我展示带有自定义照片/标记的工作示例。我需要它使用这个例子工作,我能够以另一种方式添加自定义标记,但我需要这种特定的方式与 .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 的域中。
如果此解决方案解决了您的问题,请将其标记为“已接受答案”,这样也可以帮助其他用户知道这是正确的解决方案。
推荐阅读
- mysql - 即使我能够通过终端连接,也无法通过 Xcode 应用程序连接到 MySQL 服务器
- asp.net-core - ASP.NET Core 自定义授权
- haskell - 使用 Haskell、OCaml 和 nix 语言理解 lambda 演算中的递归 let 表达式
- .htaccess - 如何从此网址中删除 id?
- javascript - 如何将 Jquery 代码转换为 React JS?
- python - 一个列表,它是 python 中另一个列表的相反概率
- javascript - 反应自定义组件未呈现
- php - PDF 不下载 - FPDF
- html - 纯 CSS 下拉菜单 - 单击菜单外时关闭下拉菜单
- intellij-idea - 运行配置错误:复合配置中没有可运行的内容