script.js
javascript
const form = document.getElementById('form');
const results = document.getElementById('results');form.addEventListener('submit', (event) => {event.preventDefault();const location = document.getElementById('location').value;// 使用 Google Places API 查找附近的修车补胎服务const request = {query: '修车补胎',location: location,radius: 1000};const service = new google.maps.places.PlacesService(document.createElement('div'));service.textSearch(request, (response, status) => {if (status === google.maps.places.PlacesServiceStatus.OK) {// 清除先前的结果results.innerHTML = '';// 在页面中显示结果for (let i = 0; i < response.results.length; i++) {const result = response.results[i];// 创建一个新的 div 元素来显示结果const div = document.createElement('div');div.classList.add('result');// 添加结果名称和地址const name = document.createElement('h3');name.innerText = result.name;div.appendChild(name);const address = document.createElement('p');address.innerText = result.formatted_address;
div.appendChild(address);// 添加一个链接,以打开 Google 地图中的位置const mapLink = document.createElement('a');mapLink.href = `${result.place_id}`;mapLink.innerText = '查看地图';div.appendChild(mapLink);// 将 div 添加到结果容器中results.appendChild(div);}}});
});style.css
css
body {font-family: Arial, sans-serif;
}h1 {margin-top: 0;
}form {display: flex;align-items: center;
}label {margin-right: 5px;
}location {width: 300px;padding: 5px;margin-right: 10px;
}results {margin-top: 10px;display: flex;flex-direction: column;
}.result {border: 1px solid ccc;padding: 10px;margin-bottom: 10px;
}.result h3 {font-weight: bold;margin-bottom: 5px;
}.result a {color: 000;text-decoration: none;
}