2017-08-06 46 views
1

我的代碼與Mapbox地圖Mapbox GL JS和GeoJSON的作爲外部文件

$(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 (evaluating '"map.geojson".features.forEach')".

有沒有辦法使用外部GeoJSON文件,自定義HTML 標記?

回答

1

既然你使用jQuery,您可以使用getJSON加載文件:

Load JSON-encoded data from the server using a GET HTTP request.

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

例子:

$.getJSON('file.geojson', function (geojson) { 
    geojson.features.forEach(function (marker) { 
     // etc 
    }); 
}); 
+0

謝謝@ IH8 –

+0

謝謝,這是有益的:) – Jozef

2

可以加載與普通的外部GeoJSON的文件mapbox addSource()。

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/