1

我有使用 Mapbox 地图设置标记的代码

$(function() {
    mapboxgl.accessToken = 'pk.###';

    var map = new mapboxgl.Map({
        container: 'map-global',
        style: '..'
    });

    var geojson = {
        "type": "FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "properties": {
                    "title": "POI Title"
                },
                "geometry": {
                    "type": "Point",
                    "coordinates": [0, 0]
                }
            }
        ]
    };

    geojson.features.forEach(function(marker) {
        // create a HTML element for each feature
        var el = document.createElement('div');
        el.className = 'marker';
        new mapboxgl.Marker(el)
            .setLngLat(marker.geometry.coordinates)
            .setPopup(new mapboxgl.Popup()
            .setHTML(marker.properties.title))
            .addTo(map);        
    });
});

它工作正常。但我想GeoJSON用作外部文件:

var geojson = 'file.geojson';

在这里我有一个问题 - 它不起作用:

TypeError: undefined is not an object (evaluate '"map.geojson".features.forEach')"。

有没有办法使用GeoJSON带有自定义 HTML 标记的外部文件?

4

2 回答 2

4

您可以使用普通的 mapbox addSource() 加载外部 geojson 文件。

map.on('load', function() {
  var url = 'http://your_geojson_file.com/some_file.geojson';
  map.addSource('source_id', { type: 'geojson', data: url});
});

请参阅此示例: https ://www.mapbox.com/mapbox-gl-js/example/live-geojson/

于 2017-08-07T11:09:55.963 回答
2

由于您使用的是 Jquery,因此您可以使用它getJSON来加载文件:

使用 GET HTTP 请求从服务器加载 JSON 编码的数据。

参考:http ://api.jquery.com/jquery.getjson/

例子:

$.getJSON('file.geojson', function (geojson) {
    geojson.features.forEach(function (marker) {
        // etc
    });
});
于 2017-08-06T23:50:45.750 回答