我正在尝试使用geojson图层构建Leaflet地图。该图层是一个巨大的文件,所以我在变量中有一个单独的geojson文件。
然而,当我运行代码时,我得到:
未捕获的ReferenceError:未定义myLayer
<script src="leaflet/mygeofile.geojson"></script> <!-- or use leaflet-src.js -->
<script src="/leaflet/leaflet.js"></script> <!-- or use leaflet-src.js -->
<script src="/leaflet/leaflet_javascript.js"></script> <!-- or use leaflet-src.js -->
<script>
$( document ).ready(function() {
//Set attributes of map (location and zoom)
var map = L.map('map').setView([51.505, -0.09], 13);
//Add base map layer, using a compatible source, with accesstoken/permissions
//for more basemaps: https://github.com/leaflet-extras/leaflet-providers
L.tileLayer('http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', {
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
maxZoom: 18,
id: 'your.mapbox.project.id',
accessToken: 'your.mapbox.public.access.token'
}).addTo(map);
//***********GEO JSON FILE IS CALLED RIGHT HERE*******************
L.geoJson(myLayer).addTo(map);
});
</script>
GEOJSON SAMPLE:
myLayer=[{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "Name": null, "description": null, "timestamp": null, "begin": null, "end": null, "altitudeMode": "relativeToGround", "tessellate": -1, "extrude": -1, "visibility": -1, "drawOrder": null, "icon": null, "STATEFP": "17", "COUNTYFP": "019", "TRACTCE": "005401", "BLKGRPCE": "2", "GEOID": "1701900540...........
}]}]
答案 0 :(得分:0)
L.GeoJSON需要Feature或FeatureCollection对象,Feature对象数组或null作为第一个参数。不是包含FeatureCollection对象的数组。剥去周围的括号(在使用之前用var关键字声明变量是一种很好的做法):
var myLayer = {
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [{
"type": "Feature", "properties": { "Name": null, "description": null, "timestamp": null, "begin": null, "end": null, "altitudeMode": "relativeToGround", "tessellate": -1, "extrude": -1, "visibility": -1, "drawOrder": null, "icon": null, "STATEFP": "17", "COUNTYFP": "019", "TRACTCE": "005401", "BLKGRPCE": "2", "GEOID": "1701900540...........
}]
}
您还在脚本标记的src属性中缺少斜杠。您可以在浏览器的开发人员工具的网络标签中检查是否所有文件都已加载。
更改:
<script src="leaflet/mygeofile.geojson"></script>
要
<script src="/leaflet/mygeofile.geojson"></script>