javascript - 使用自动完成搜索后缩放

标签 javascript jquery jquery-ui leaflet geojson

搜索后如何放大 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/

相关文章:

javascript - 在通过 AJAX 传递给 JavaScript 函数的 HTML 字符串中插入 PHP 变量?

javascript - 并非所有内联 JavaScript 都通过 AJAX 执行

单击时停止的 Javascript 发光/脉动效果

java - 如何查明是否选中了多个复选框

javascript - Jquery CSS 作用域在 selectmenu 上不能正常工作

asp.net - 大数据集的自动完成优化

javascript - 防止用户在测验应用程序中重新加载/刷新页面的方法

javascript - 根据单击的按钮输出到特定容器

javascript - 显示阵列中的 6 个(不同的)图像,不显示重复项并每 x 秒重新加载一次

javascript - 如何将一个 div 拖放到另一个 div 上