搜索后如何放大 map 上找到的值?我的代码是:
$("#txtSearch").autocomplete({
source: setoresComerciais.features.map(function(d){
return d.properties.sco_num_sc + " - " + d.properties.sco_dsc_loc
}),
select: function(event, ui){
map.fitBounds(stComerciaisLayer.getBounds(ui.item.value));
}
});
首先,我得到return d.properties.sco_num_sc + "- "+ d.properties.sco_dsc_loc
,此返回例如:"1 - FORTALEZA"
之后,我使用 select,其中有参数 ui,ui.item.value
何时返回 "1 - FORTALEZA"
,所以这样:
map.fitBounds(stComerciaisLayer.getBounds(ui.item.value));
地点:
stComerciaisLayer = L.geoJSON(setoresComerciais, {
style: function (feature) {
return feature.properties && feature.properties.style;
},
onEachFeature: onEachFeature,
(...)
它的目的是返回我想要的内容,即搜索结果和放大结果,但不起作用。我做错了什么?
最佳答案
这一行:
map.fitBounds(stComerciaisLayer.getBounds(ui.item.value));
不会按预期工作。从 API 文档来看, getBounds() 不接受任何参数,它只是返回您正在使用的层的边界。由于该图层包含所有 geojson,因此这是行不通的。
相反,我们可以从 geojson FeatureCollection 中获取所选要素的 geojson,并从中创建一个图层(我们不需要将其添加到 map 中),以便我们可以找到其边界并相应地更新 map 。
我们如何在 geojson 中获得正确的特征?有几种方法,我们可以使用字典,或者我们可以向自动完成函数源添加额外的数据(如其他答案中所建议的)。我将遵循其他答案中的引导,但使用功能的增量并继续使用 .map() :
source: setoresComerciais.features.map(function(d,i){
return {
label: d.properties.sco_num_sc + " - " + d.properties.sco_dsc_loc,
id: i
};
这里 .map 采用两个变量:d
是正在处理的特征数组中的当前项,i
是该特征的索引。通过索引,我们可以轻松访问要素数组中的正确项目,从中创建一个图层,并将 map 边界适合该要素的图层:
select: function(event, ui){
var feature = setoresComerciais.features[ui.item.id]; // get the geojson
var featureLayer = L.geoJSON(feature) // create a layer from it
map.fitBounds(featureLayer.getBounds()); // resize the map
}
总而言之,这给了我们:
$("#txtSearch").autocomplete({
source: setoresComerciais.features.map(function(d,i){
return {label: d.properties.sco_num_sc + " - " + d.properties.sco_dsc_loc, id: i };
}),
select: function(event, ui){
var feature = setoresComerciais.features[ui.item.id];
var featureLayer = L.geoJSON(feature)
map.fitBounds(featureLayer.getBounds());
}
});
关于javascript - 使用自动完成搜索后缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47419475/