查找附近的汽车美容 (查找附近的汽修店)

长沙桑拿 04-11 阅读:51 评论:0
查找附近的汽车美容 (查找附近的汽修店)

结果:

javascript const searchForm = document.getElementById("search-form"); const resultList = document.getElementById("result-list");//定义API密钥(请替换为您的Google Places API密钥) const API_KEY = "YOUR_API_KEY_HERE";// 获取用户位置 function getLocation(location) {return new Promise((resolve, reject) => {if (navigator.geolocation) {navigator.geolocation.getCurrentPosition((position) => resolve({ lat: position.coords.latitude, lng: position.coords.longitude }),(error) => reject(error));} else {resolve({ lat: 0, lng: 0 });}}); }// 使用Google Places API搜索汽车美容 function searchAutoDetailing(location, radius) {return fetch(`${location.lat},${location.lng}&radius=${radius}&key=${API_KEY}`).then((response) => response.json()).then((data) => data.results); }// 将搜索结果显示在页面上 function displayResults(results) {resultList.innerHTML = "";for (let result of results) {const listItem = document.createElement("li");const name = document.createElement("h3");name.innerText = result.name;const address = document.createElement("p");address.innerText = result.formatted_address;const phone = document.createElement("p");phone.innerText = result.formatted_phone_number;listItem.appendChild(name);listItem.appendChild(address);listItem.appendChild(phone);resultList.appendChild(listItem);} }// 处理搜索提交 searchForm.addEventListener("submit", (event) => {event.preventDefault();const location = document.getElementById("location").value;// 获取用户位置,并开始搜索getLocation(location).then((userLocation) => {// 将用户位置和半径(以米为单位)传递给搜索函数const radius = 5000; // 搜索半径5公里return searchAutoDetailing(userLocation, radius);}).then(displayResults).catch((error) => {console.error(error);alert("抱歉,出错了。请重试。");}); });
版权声明

本文仅代表作者观点,不代表长沙桑拿立场。
本文系作者授权发表,未经许可,不得转载。