美文网首页
flutter 集成高德地图搜索

flutter 集成高德地图搜索

作者: 代瑶 | 来源:发表于2021-07-14 16:46 被阅读0次
image.png

利用到的 高德搜索 插件

amap_search_fluttify: ^0.16.2
https://pub.flutter-io.cn/packages/amap_search_fluttify

想要达到搜索关键字用这个API即可
AmapSearch.instance.searchKeyword 但是直接使用的话并且需要做到输入实时搜索就存在问题了。
当我输入 在搜索还未返回结果时输入 , 然后接着又输入 , 这个时候会请求三次搜索, 分别是 菊泉 菊泉街,
但其实我只需要搜索菊泉街这个地方, 而搜索又是根据有字的情况自动触发的, 那么可以去掉的一次多余搜索就是 菊泉了。
而快速的输入或者清除输入框里面的内容, 在搜索结果返回较慢的情况会出现展示列表数据错乱的问题. 总之这里需要一个特殊的处理。

我最开始想到的是使用Queue 来完成, 将所有的新输入加入到队列中, 然后取出队列中的最后一条数据。发现并不好实现, 主要矛盾是什么时候来调用搜索并不好抉择

最终实现方法

class SearchObj {
  String keyword;
  Function searchFun;

  SearchObj(this.keyword, this.searchFun);
}

///当前的搜索
SearchObj _currentSearchIng;

///排队中的
SearchObj _lineSearchIng;

void onSearchKeyWord(String inputContent) async {
    vm.currentSearchKeyWord = inputContent;

    if (TextUtil.isEmpty(inputContent)) {
      vm.searchListData = [];
      vm.isSearchIng = false;

      _currentSearchIng = null;
      _lineSearchIng = null;
      return;
    }
    // final poiList = await AmapSearch.instance.searchKeyword(
    //   // LatLng(31.2211, 121.398),
    //   /* keyword: */
    //   inputContent,
    //   city: "上海",
    // );

    // AmapSearch.instance.fetchInputTips(inputContent, city: "上海").then((results) {
    SearchObj _searchObj = SearchObj(inputContent, () {
      print('准备搜索' + inputContent);
      vm.isSearchIng = true;

      try {
        AmapSearch.instance.searchKeyword(inputContent, city: "上海").then((results) {
          vm.isSearchIng = false;
          if (vm.currentSearchKeyWord != inputContent) {
            print('当前关键字是:${vm.currentSearchKeyWord} 忽略之前的:$inputContent');
          } else {
            vm.searchListData = results;
            print('结束搜索' + inputContent);
          }

          ///如果有排队中的数据,则调用回调
          if (_lineSearchIng != null) {
            _lineSearchIng.searchFun.call();
            _lineSearchIng = null;
          }
        });
      } catch (e) {
        vm.isSearchIng = false;
      }
    });

    if (vm.isSearchIng) {
      ///如果正在搜索中
      _lineSearchIng = _searchObj;
      print('log_有搜索任务正在执行....');
    } else {
      ///如果已经搜索完成,并显示结果了
      _currentSearchIng = _searchObj;
      _currentSearchIng.searchFun.call();
      _lineSearchIng = null;
      print('log_直接变成currentSearch....');
    }
  }

相关文章

网友评论

      本文标题:flutter 集成高德地图搜索

      本文链接:https://www.haomeiwen.com/subject/tlbypltx.html