我是Javascript和传单的初学者。首先,我像这样制作文件geojson.js
var data={
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"id": 1,
"properties": {
"Name": "Germany",
"description": "",
"timestamp": "",
"begin": "",
"end": "",
"altitudeMode": "clampToGround",
"tessellate": 1,
"extrude": -1,
"visibility": -1
},
"geometry": {
"type": "Point",
"coordinates": [
51.329219337279405,
10.454119349999928
]
}
}
]
}
并像这样访问他们的坐标
points[0] = data.features[0].geometry.coordinates[0];
points[1] = data.features[0].geometry.coordinates[1];
这没关系,但是我想制作几个geojson,将它们存储在同一个文件夹中并通过url leaflet/geojson.js
访问它们,而不是通过http或ajax访问它们。像这样:
var data = $.getJSON( "leaflet/geojson.js", function(json) {
points[0] = json.features[0].geometry.coordinates[0];
})
我可以这样做吗?
提前致谢!
答案 0 :(得分:4)
如果你想将geojson存储在一个单独的文件中,就像它们在这里http://leafletjs.com/examples/geojson-example.html一样,那么你将不得不以某种方式获取它,就像浏览器获取你的js文件以初始化传单一样。
正如charlietfl所说,只需在脚本标记上方添加脚本标记,就像在我发布的链接中一样。然后,您可以在不使用任何提取方法的情况下引用数据var,因为它已在页面加载时获取。或者,只需将var数据添加到与init脚本相同的文件中。
<script type="text/javascript" src="leaflet/geojson.js">
var data = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"id": 1,
"properties": {
"Name": "Germany",
"description": "",
"timestamp": "",
"begin": "",
"end": "",
"altitudeMode": "clampToGround",
"tessellate": 1,
"extrude": -1,
"visibility": -1
},
"geometry": {
"type": "Point",
"coordinates": [
51.329219337279405,
10.454119349999928
]
}
}
]
};
var data2 = {
...
};
</script>
<script>
var map = L.map('map').setView([39.74739, -105], 13);
L.tileLayer('http://{s}.tile.cloudmade.com/{key}/22677/256/{z}/{x}/{y}.png', {
attribution: 'Map data © 2011 OpenStreetMap contributors, Imagery © 2012 CloudMade',
key: 'BC9A493B41014CAABB98F0471D759707'
}).addTo(map);
L.geoJson(data).addTo(map);
L.geoJson(data2).addTo(map);
</script>