首页 > 解决方案 > 如何使用另一个属性返回特定的 Geojson 特征属性,例如按名称返回经度属性?

问题描述

我正在尝试使用 Mapbox 创建一个界面,该界面可以缩放到用户使用此功能单击的多边形,同时还更新非地图 div 中的下拉菜单值。

当用户单击地图中的多边形/城镇时,它将使用此map.on('click...)脚本缩放到正确的特征。

   map.on('click', 'Map Layer', function (e) {
            townnames = e.features[0].properties.Object_Name;
            townlat = e.features[0].properties.Object_latitude;
            townlong = e.features[0].properties.Object_longitude;
      map.setFilter('LayerFiltered', ['==', 'TOWN_NAME', Object_Name]);
      map.setFilter('LayerClicked', ['!=', 'TOWN_NAME', Object_Name]);
      map.setLayoutProperty('LayerFiltered', 'visibility', 'visible');
      map.flyTo({
      center: [
        townlong, townlat], 
        zoom : 11.5
});

但是我正在尝试使用下拉菜单触发相同的功能。

我已经弄清楚如何使用下拉菜单中选项中的内部 HTML 值过滤图层,并将它们设置为等于 setFilter 中的“Object_Name”。但是有什么方法可以从与基于“TOWN_NAME”等属性之一的特征关联的geojson返回其他属性?

换句话说,我可以使用下拉菜单中的变量,而不是e.features[0].properties.Object_longitude在用户单击某个功能时返回,而是在他们单击下拉菜单中的关联值时返回一些内容,效果如下:"features.TOWN_NAME=DROPDOWN_VALUE_NAME".properties.Object_longitude"

如果不清楚,我很抱歉。

标签: javascriptmapboxmapbox-gl-js

解决方案


下拉菜单不会触发 load 事件。您必须将上述工作分解为由地图和下拉列表的处理程序调用的通用方法。

编辑:下拉菜单没有被分配点击事件,需要给一个监听器来调用一个函数,该函数也被地图对象点击监听器调用。

演示

// Add an event listener for the links in the sidebar listing
                listings.addEventListener('change', function () {
                    // Update the currentFeature to the store associated with the clicked link
                    var clickedListing = data.features[listings.selectedIndex];
                    // 1. Fly to the point associated with the clicked link
                    flyToStore(clickedListing);
                    // 2. Close all other popups and display popup for clicked store
                    createPopUp(clickedListing);
                });
        }


// Add an event listener for when a user clicks on the map
        map.on('click', function (e) {
            // Query all the rendered points in the view
            var features = map.queryRenderedFeatures(e.point, { layers: ['locations'] });
            if (features.length) {
                var clickedPoint = features[0];
                // 1. Fly to the point
                flyToStore(clickedPoint);
                // 2. Close all other popups and display popup for clicked store
                createPopUp(clickedPoint);

            // Find the index of the store.features that corresponds to the clickedPoint that fired the event listener
            var selectedFeature = clickedPoint.properties.address;

            for (var i = 0; i < stores.features.length; i++) {
                if (stores.features[i].properties.address === selectedFeature) {
                    selectedFeatureIndex = i;
                }
            }
            // Select the correct list item using the found index
            var listings = document.getElementById('mySelect').selectedIndex = selectedFeatureIndex ;
        }
    });

推荐阅读