Add Bing Map Autosuggest API to multiple fields in a form

痞子三分冷 提交于 2019-12-06 15:46:59

It appears Autosuggest is supported to be attached per a single input box only. Meaning in case of multiple input boxes, the instance of AutosuggestManager class should be created per every input box. The following example demonstrates it:

function bingMapsReady() {
  Microsoft.Maps.loadModule("Microsoft.Maps.AutoSuggest", {
    callback: onLoad,
    errorCallback: logError,
    credentials: 'Ap12Gwv9esg5iXgfAh5Ehlbf36MZ-O8051Sl66Zm6glGwq7PSaaKgGPpcOUEGICy'
  });

  function onLoad() {
    var options = { maxResults: 8 };
    initAutosuggestControl(options, "searchBox", "searchBoxContainer");
    initAutosuggestControl(options, "searchBoxAlt", "searchBoxContainerAlt");
  }
}

function initAutosuggestControl(
  options,
  suggestionBoxId,
  suggestionContainerId
) {
  var manager = new Microsoft.Maps.AutosuggestManager(options);
  manager.attachAutosuggest(
    "#" + suggestionBoxId,
    "#" + suggestionContainerId,
    selectedSuggestion
  );

  function selectedSuggestion(suggestionResult) {
    document.getElementById(suggestionBoxId).innerHTML =
      suggestionResult.formattedSuggestion;
  }
}


function logError(message) {
  console.log(message);
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<script
  type="text/javascript" src="https://www.bing.com/api/maps/mapcontrol?callback=bingMapsReady" async defer></script>

<form>
  <div class="form-group">
    <label for="searchBox">Address</label>
    <div id="searchBoxContainer"><input class="form-control" type="text" id="searchBox" /></div>
  </div>
  <div class="form-group">
        <label for="searchBoxAlt">Alternative Address</label>
        <div id="searchBoxContainerAlt"><input class="form-control" type="text" id="searchBoxAlt" /></div>
      </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

Demo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!