hello i am tej i am working on a app which needs a location feature i added a text box and whenever i type something in that textbox(any places/address) i just want it to get automatically filled suggestions like any google maps or something
i tried bing maps api , i took bing maps api key and tried to get it integrate it with my app using html and javascript but in the end its showing runtime error and i dont know what to do
this is my html code for the form
<script type="text/javascript">
function loadBingMaps() {
const script = document.createElement('script');
script.src = `https://www.bing.com/api/maps/mapcontrol?callback=bingMapsReady&key=API KEY`;
document.body.appendChild(script);
}
function bingMapsReady() {
console.log("Bing Maps API loaded and ready.");
}
function getSuggestions(query, callback) {
const url = `https://dev.virtualearth.net/REST/v1/Autosuggest?query=${query}&key=API KEY`;
fetch(url)
.then(response => response.json())
.then(data => {
if (data.resourceSets.length > 0 && data.resourceSets[0].resources.length > 0) {
const suggestions = data.resourceSets[0].resources[0].value;
callback(suggestions);
}
})
.catch(error => console.error('Error fetching autocomplete suggestions:', error));
}
function handleInputChange(event) {
const query = event.target.value;
if (query.length > 2) {
getSuggestions(query, suggestions => {
// Update Anvil RepeatingPanel with suggestions
const pySuggestions = suggestions.map(suggestion => suggestion.address);
anvil.call('update_suggestions', pySuggestions);
});
}
}
document.addEventListener('DOMContentLoaded', (event) => {
loadBingMaps();
const textBox = document.querySelector("[role='autocomplete_text_box']");
if (textBox) {
const inputElement = textBox.querySelector("input");
if (inputElement) {
inputElement.addEventListener("input", handleInputChange);
} else {
console.error("Input element within TextBox not found.");
}
} else {
console.error("TextBox with role 'autocomplete_text_box' not found.");
}
});
</script>
MY python code for the form:
from ._anvil_designer import dashboardTemplate
from anvil import *
import anvil.server
from anvil.js import window
class dashboard(dashboardTemplate):
def __init__(self, **properties):
self.init_components(**properties)
# Set the role attribute programmatically
self.text_box_1.role = "autocomplete_text_box"
self.text_box_1.set_event_handler('change', self.on_text_change)
self.repeating_panel_1.items = [ ]
def on_text_change(self, **event_args):
text = self.text_box_1.text
if len(text) > 2:
suggestions = anvil.server.call('fetch_suggestions', text)
self.update_suggestions(suggestions)
def update_suggestions(self, suggestions):
self.repeating_panel_1.items = [{'text': suggestion} for suggestion in suggestions]
def primary_color_1_click(self, **event_args):
"""This method is called when the button is clicked"""
open_form('dashboard.aviailable_Hospital_Address')
def primary_color_1_copy_click(self, **event_args):
"""This method is called when the button is clicked"""
open_form('dashboard.availabe_vehical_services')
def primary_color_1_copy_2_click(self, **event_args):
"""This method is called when the button is clicked"""
open_form('dashboard.available_zym_address')
def button_1_click(self, **event_args):
"""This method is called when the button is clicked"""
pass
def map_1_bounds_changed(self, **event_args):
"""This method is called when the viewport bounds have changed."""
pass
server code
import anvil.tables as tables
import anvil.tables.query as q
from anvil.tables import app_tables
import anvil.server
import anvil.http
# This is a server module. It runs on the Anvil server,
# rather than in the user's browser.
#
# To allow anvil.server.call() to call functions here, we mark
# them with @anvil.server.callable.
# Here is an example - you can replace it with your own:
#
# @anvil.server.callable
# def say_hello(name):
# print("Hello, " + name + "!")
# return 42
#
@anvil.server.callable
def fetch_suggestions(query):
# Fetch suggestions from the Bing Maps API
url = f"https://dev.virtualearth.net/REST/v1/Autosuggest?query={query}&key=YOUR_BING_MAPS_API_KEY"
response = anvil.http.request(url, json=True)
suggestions = [item['address']['formattedAddress'] for item in response['resourceSets'][0]['resources'][0]['value']]
return suggestions