我想知道是否可以将数据集直接导入到我的代码(javascript)中,因为我想为用户按下某个功能时显示给定数据集的条件。
fetch('http://localhost:portOfDatabase/path')
.then(resp => resp.json())
.then(r => {
//use r which holds the response from your database
})
JSON.parse()
从字符串格式的数据中创建对象。然后使用该对象提取所有要显示的信息。 Here are some examples从w3schools:
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
obj.name // "John"
obj.age // 30
obj.city // "New York"
作为其他答案,您可以从JSON文件加载数据。请注意,数据必须为geoJSON format。
这将在运行时创建geoJSON数据源。但是您也可以将其指向源文件。 (请参阅第二个代码段)
map.addSource('route', {
'type': 'geojson',
'data': {
'type': 'Feature',
'properties': {},
'geometry': {
'type': 'LineString',
'coordinates': [
[-122.48369693756104, 37.83381888486939],
[-122.48348236083984, 37.83317489144141],
[-122.48339653015138, 37.83270036637107],
[-122.48356819152832, 37.832056363179625]
]
}
}
)
来自文件:map.addSource(<sourcename>, { 'type': 'geojson', 'data': <URL> });
也请参见以下示例: