如何在开放层3中添加搜索框

How to add a search box in open layers 3

我尝试了一个开放层 3 的示例,它只添加了一个搜索框但不搜索位置,下面是代码 -

<div id="search" style="position: absolute; top: 10px; right: 10px; padding: 5px; background-color: rgba(255,255,255,0.5);">
      <input type="text" placeholder="place" style="width: 200px">
      <button type="button">Search</button>
    </div>

这是我尝试过的另一种方法,但是上面写着 "geocoder is undefined",有人可以推荐任何其他方法吗?

var geocoder = new Geocoder('nominatim', {
  provider: 'mapquest',
  key: 'osm',
  lang: 'pt-BR', //en-US, fr-FR
  placeholder: 'Search for ...',
  targetType: 'text-input',
  limit: 5,
  keepOpen: true
});
map.addControl(geocoder);
geocoder.on('addresschosen', function(evt){
  var feature = evt.feature,
      coord = evt.coordinate,
      address = evt.address;
  // some popup solution
  content.innerHTML = '<p>'+ address.formatted +'</p>';
  overlay.setPosition(coord);
});

您似乎试图通过 Jonatas Walker 实现 Geocoder 插件:https://github.com/jonataswalker/ol-geocoder(或者在最新版本的 openlayers 中实现了这个?-您从哪里获取这个示例?)

在这种情况下,我认为您缺少两件事:

1) 在模板中添加 css 和 javascript 代码或 index.html:

<link href="https://cdn.jsdelivr.net/npm/ol-geocoder@latest/dist/ol-geocoder.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/ol-geocoder"></script>

2) 创建一个帐户并在 Mapquest 注册密钥,因为这对该提供商是强制性的,或者尝试使用不需要密钥的其他提供商,例如 osm:

var geocoder = new Geocoder('nominatim', {
  provider: 'osm', //change it here
  lang: 'en-US',
  placeholder: 'Search for ...',
  targetType: 'text-input',
  limit: 5,
  keepOpen: true
});

最简单的方法是使用这个库,https://github.com/Viglino/ol-ext,它还带有大量扩展。

搜索框的例子https://viglino.github.io/ol-ext/examples/search/map.control.searchnominatim.html