问题
I have created a stackoverflow snippet inside an answer, but get an error if I am using map.queryRenderedFeatures()
. Outside the snippet in the index.html
all works fine. Could it be a CORS problem ? I got no error message except an undefined return. The strange thing is that sometimes it is working in FullPage Modus
Here goes my snippet:
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>
来源:https://stackoverflow.com/questions/40081554/stackoverflow-snippet-throws-an-error-but-outside-it-is-working