css
/ 重置样式 /{margin: 0;padding: 0;box-sizing: border-box;
}/ 整体样式 /body {font-family: Arial, sans-serif;color: 333;
}h1, h2, h3 {font-weight: bold;
}/ 页眉样式 /header {background-color: 000;color: fff;padding: 10px 20px;
}h1 {margin-top: 0;
}/ 主体内容样式 /main {max-width: 960px;margin: 0 auto;padding: 20px;
}/ 搜索表单样式 /search-form {background-color: f5f5f5;padding: 20px;
}label {display: block;margin-bottom: 5px;
}input[type="text"] {width: 100%;padding: 5px;border: 1px solid ccc;
}button[type="submit"] {float: right;padding: 5px 10px;background-color: 000;color: fff;border: none;
}/ 搜索结果样式 /results {margin-top: 20px;
}h2 {margin-bottom: 10px;
}ul {list-style-type: none;padding: 0;
}li {margin-bottom: 10px;
}/ 页脚样式 /footer {background-color: 000;color: fff;padding: 10px 20px;
}
javascript
// 获取 DOM 元素
const locationInput = document.getElementById('location');
const resultsList = document.querySelector('results ul');// 创建 XMLHttpRequest 对象
const xhr = new XMLHttpRequest();// 添加事件监听器
locationInput.addEventListener('keyup', function(e) {// 检查输入是否为空if (locationInput.value === '') {resultsList.innerHTML = '';return;}// 打开一个 HTTP 请求xhr.open('GET', `${locationInput.value}&key=[API_KEY]`);// 发送请求xhr.send();
});// 添加一个 readystatechange 事件监听器
xhr.onreadystatechange = function() {if (xhr.readyState === 4 && xhr.status === 200) {// 解析响应const response = JSON.parse(xhr.responseText);// 清除结果列表resultsList.innerHTML = '';// 遍历结果并将其添加到列表中for (const place of response.candidates) {const li = document.createElement('li');li.innerHTML = `
${place.name}
${place.formatted_address}
`;resultsList.appendChild(li);}}
};