如何在Mapbox GL JS中为Geocoder添加外部数据

时间:2019-06-10 15:16:05

标签: javascript mapbox mapbox-gl-js

我正在运行一些设施及其名称和坐标数据的位置地图。我希望地址解析器能够搜索设施的名称。

Mapbox有一个很好的例子,但是他们的例子展示了一个用例,其中数据集被加载到实际代码中。我的数据集更大,当前位于项目文件夹中的.geojson文件中。

如何转换此代码以使其适用于我的示例?

我尝试使用

将数据集回调到地址解析器代码中
  var myData =getSource('BRdata');

然后致电

 for (var i = 0; i < myData.features.length; i++) {
    var feature = myData.features[I];

// handle queries with different capitalization than the source data by calling toLowerCase()
     if (feature.properties.HandlerId.toLowerCase().search(query.toLowerCase()) !== -1) {

     feature['place_name'] = '? ' + feature.properties.HandlerId;
     feature['center'] = feature.geometry.coordinates;
      matchingFeatures.push(feature);
 }
}
  return matchingFeatures;
}

将数据导入地址解析器,但无法正常工作。我收到错误“

  

myData未定义

在这里可以看到一个正在工作的矮人 https://plnkr.co/edit/UUaf6OCgvoavwshdUdN9?p=preview

  

预期结果:Geocoder将.geojson数据调用到搜索字段中   实际结果:Geocoder找不到.geojson。

     

错误:“未定义myData”

edit添加了此代码,其中包括新的var myData:

    function forwardGeocoder(query) {
  // Fetch data on server and serve me the raw geojson
  var myData = fetch('test-plnkr.json').then(res => res.json());
    var matchingFeatures = [];
    for (var i = 0; i < myData.features.length; i++) {
    var feature = myData.features[i];
    // handle queries with different capitalization than the source data by calling toLowerCase()
    if (feature.properties.HandlerId.toLowerCase().search(query.toLowerCase()) !== -1) {
    // add a tree emoji as a prefix for custom data results
    // using carmen geojson format: https://github.com/mapbox/carmen/blob/master/carmen-geojson.md
    feature['place_name'] = '? ' + feature.properties.HandlerId;
    feature['center'] = feature.geometry.coordinates;
    //feature['place_type'] = ['park'];
    matchingFeatures.push(feature);
    }
    }
    return matchingFeatures;
    }

map.addControl(new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
localGeocoder: forwardGeocoder,
zoom: 14,
placeholder: "Enter search e.g. Lincoln Park",
mapboxgl: mapboxgl
}));

0 个答案:

没有答案