搜索附近的大货车修理厂
搜索结果:
javascript
// script.js
const form = document.querySelector('form');
const results = document.querySelector('results');
const listOfRepairShops = document.querySelector('list-of-repair-shops');// 使用 HTML5 地理位置 API 获取用户的当前位置
function getLocation() {if (navigator.geolocation) {navigator.geolocation.getCurrentPosition(showPosition, showError);} else {alert('您的浏览器不支持地理位置。');}
}// 显示用户当前位置
function showPosition(position) {const latitude = position.coords.latitude;const longitude = position.coords.longitude;searchRepairShops(latitude, longitude);
}// 显示定位错误
function showError(error) {switch (error.code) {case error.PERMISSION_DENIED:alert('您拒绝了访问您当前位置的请求。');break;case error.POSITION_UNAVAILABLE:alert('无法获取您的当前位置。');break;case error.TIMEOUT:alert('获取您的当前位置超时。');break;case error.UNKNOWN_ERROR:alert('获取您的当前位置时发生未知错误。');break;}
}// 根据用户的当前位置搜索附近的修理厂
function searchRepairShops(latitude, longitude) {const request = new XMLHttpRequest();const apiUrl = `${latitude},${longitude}&radius=5000&type=car_repair&key=YOUR_API_KEY`;request.open('GET', apiUrl, true);request.send();request.onload = function() {if (request.status === 200) {const data = JSON.parse(request.responseText);const repairShops = data.results;// 清空以前的结果listOfRepairShops.innerHTML = '';// 将修理厂添加到列表中for (let i = 0; i < repairShops.length; i++) {const repairShop = repairShops[i];const listItem = document.createElement('li');const name = document.createElement('h3');name.textContent = repairShop.name;const address = document.createElement('p');address.textContent = repairShop.vicinity;const link = document.createElement('a');link.setAttribute('href', repairShop.url);link.textContent = '查看网站';listItem.appendChild(name);listItem.appendChild(address);listItem.appendChild(link);listOfRepairShops.appendChild(listItem);}} else {alert('搜索最近的修理厂时出错。');}};
}// 在页面加载时获取用户的位置
window.onload = getLocation();