我在答案中创建了一个stackoverflow代码段,但如果我使用map.queryRenderedFeatures()
则会出错。在index.html
的片段之外,一切正常。这可能是一个CORS问题吗?除了未定义的返回,我没有收到任何错误消息。奇怪的是,有时它在 FullPage Modus
这是我的片段:
mapboxgl.accessToken = 'pk.eyJ1IjoicHJheWVyIiwiYSI6ImI3OGRjZjcyY2JiZTUzODMwZWUxZDdiNjRiMWE4NjI5In0.zETX-x6-XPpAv3zt4MiFwg';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/prayer/ciub6rm2j004v2iodiej359ox',
center: [14.5, 47],
zoom: 6
});
map.on('click', function (e) {
var features = map.queryRenderedFeatures({
layers:['roads-bm6ga5'],
filter: ["==", "id", 1]
});
document.getElementById('features').innerHTML = '<b>Road with ID</b> ' + features[0].properties.id + ' has the coordinates:' +
'<br>' +JSON.stringify(features[0].geometry.coordinates, null, 2);
});
map.on('load', function (e) {
alert("Click in the map to show coordinates of road with ID 1")
});
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
#features {
position: absolute;
top: 0;
right: 0;
bottom: 0;
width: 300px;
overflow: auto;
background: rgba(255, 255, 255, 0.8);
}
#map canvas {
cursor: crosshair;
}
<link href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.26.0/mapbox-gl.css" rel="stylesheet"/>
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.26.0/mapbox-gl.js"></script>
<div id='map'></div>
<pre id='features'></pre>