无法从外部geojson将属性获取到mapbox

问题描述 投票:0回答:1

我已经从mapbox复制并调整了此示例:https://docs.mapbox.com/mapbox-gl-js/example/filter-markers/

一切正常,但我想将geojson作为外部文件。

所以我更改此代码:

var places = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'properties': {
'icon': 'theatre'
},
'geometry': {
'type': 'Point',
'coordinates': [-77.038659, 38.931567]
}
},
]
};

带有此:

var places = '../images/destinations.geojson';

并且我在DevTools中收到此错误:Uncaught TypeError:无法读取未定义的属性'forEach'。

剩下的代码(我得到了错误)是这样的:

map.on('load', function() {
// Add a GeoJSON source containing place coordinates and information.
map.addSource('places', {
'type': 'geojson',
'data': places
});

places.features.forEach(function(feature) {
var symbol = feature.properties['icon'];
var layerID = 'poi-' + symbol;

// Add a layer for this symbol type if it hasn't been added already.
if (!map.getLayer(layerID)) {
map.addLayer({
'id': layerID,
'type': 'symbol',
'source': 'places',
'layout': {
'icon-image': symbol + '-15',
'icon-allow-overlap': true
},
'filter': ['==', 'icon', symbol]
});
mapbox geojson
1个回答
0
投票

加载外部geoJSON文件的一种方法是使用d3js。请参见以下示例,该示例取自this mapbox example。此示例将为geoJSON文件中给出的坐标画一条线。

您应该能够使用forEach循环遍历data.features

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Load from an external geoJSON</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://api.mapbox.com/mapbox-gl-js/v1.8.0/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v1.8.0/mapbox-gl.css" rel="stylesheet" />
<style>
	body { margin: 0; padding: 0; }
	#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<div id="map"></div>
 
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
	mapboxgl.accessToken = '<access_token>';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/satellite-v9',
zoom: 0
});
 
map.on('load', function() {
// We use D3 to fetch the JSON here so that we can parse and use it separately
// from GL JS's use in the added source. You can use any request method (library
// or otherwise) that you want.
d3.json(
'https://docs.mapbox.com/mapbox-gl-js/assets/hike.geojson', //the geoJSON data file
function(err, data) {
if (err) throw err;
 
// save full coordinate list for later
var coordinates = data.features[0].geometry.coordinates;
 
// start by showing just the first coordinate
data.features[0].geometry.coordinates = [coordinates[0]];
 
// add it to the map
map.addSource('trace', { type: 'geojson', data: data });
map.addLayer({
'id': 'trace',
'type': 'line',
'source': 'trace',
'paint': {
'line-color': 'yellow',
'line-opacity': 0.75,
'line-width': 5
}
});
 
 


}
);
});
</script>
 
</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.