Addressable + Awesomplete

by addressable

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.1.7/awesomplete.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.1.7/awesomplete.min.css">
<h1>
  <a href="https://projects.verou.me/awesomplete/" target="_blank">Awesomplete</a>
  Example
</h1>
  <p>
    For demo purposes, set your <a href="https://www.addressable.dev/account">API key</a> here then, select country and search any address <br/>
    <input type="password" id="apikey" class="form-control" placeholder="Your API Key..." autocomplete="off">
  </p>

<input class="awesomplete" id="query" placeholder="Type to search..."/>

<select id="country_code">
  <option value="AU" selected="">Australia</option>
  <option value="NZ">New Zealand</option>
</select>

JavaScript

var key = "enter_your_key_here" // must UPDATE to your API key from https://www.addressable.dev/account

const queryInput = document.querySelector("#query")

const awesomplete = new Awesomplete(queryInput, {
  filter: () => {
    // We will provide a list that is already filtered ...
    return true
  },
  sort: false, // ... and sorted.
  list: [],
})

function selectAutocomplete(event) {
  console.log("selected: " + event.text.value)
}
Awesomplete.$.bind(queryInput, {
  "awesomplete-selectcomplete": selectAutocomplete,
})

queryInput.addEventListener("input", (event) => {
  const inputText = event.target.value
  console.log("query: " + inputText)

  if (inputText.length < 2 || inputText.length > 10) return // Avoid making API calls for very short or long inputs

	var key = document.querySelector("#apikey").value;
	if (key == ''){
  	console.log("Set the API key to run live requests");
    return
  }

  fetch(
    `https://api.addressable.dev/v2/autocomplete?api_key=${key}&country_code=${document.querySelector("#country_code").value}&q=${encodeURIComponent(inputText)}`,
  )
    .then((response) => {
      if (!response.ok) throw new Error("Network response was not ok")
      return response.json()
    })
    .then((suggestions) => {
      awesomplete.list = suggestions.map((item) => item.formatted)
      awesomplete.evaluate()
    })
    .catch((error) => {
      console.error("Error fetching autocomplete suggestions:", error)
    })
})