我有一个用于搜索商店编号以在 map 上找到其位置的输入。 JSON 是 hosted here , 但我会在下面留下一个片段。
"22": {
"Lat": "43.1022902",
"Address": "3065 NY-50 Saratoga Springs NY 12866 USA",
"Long": "-73.7377407"
},
"23": {
"Lat": "40.3581539",
"Address": "2767 Papermill Rd Reading PA 19610 USA",
"Long": "-75.9850194"
},
"24": {
"Lat": "40.1893263",
"Address": "347 Washington Rd Washington PA 15301 USA",
"Long": "-80.2265591"
},
"26": {
"Lat": "38.0240453",
"Address": "1968 Pavilion Way Lexington KY 40509 USA",
"Long": "-84.41592919999999"
}
该函数旨在获取搜索值并获取该值的 lat
和 long
值。所以 searchString = 23
会给出以下内容;
"Lat": "40.3581539",
"Address": "2767 Papermill Rd Reading PA 19610 USA",
"Long": "-75.9850194"
下面是我尝试过的:
$('#search-bar').submit(function () {
searchString = $("#search").val();
$.getJSON(allStoresJson, function (data) {
query = allStoresJson[searchString]
console.log(query)
lat = query.Lat
long = query.Long
})
var point = new L.LatLng(lat, long);
map.setView(point, 11, {
animation: true
})
return false;
});
最佳答案
data
包含解析 JSON 响应所产生的对象。
由于 $.getJSON
是异步的,您不能在其外部使用回调中设置的变量。您需要在回调中调用 map.setView()
。
$('#search-bar').submit(function() {
searchString = $("#search").val();
$.getJSON(allStoresJson, function(data) {
query = data[searchString];
console.log(query)
lat = query.Lat
long = query.Long
var point = new L.LatLng(lat, long);
map.setView(point, 11, {
animation: true
})
})
return false;
});
关于javascript - 将输入值与数组中的 JSON 对象匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52394920/