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

武汉洗浴 04-13 阅读:50 评论:0
查找附近的汽车 (查找附近的汽修店)
javascript // script.js// 格式化地址 const formatAddress = (address) => {return address.replace(/ /g, "+").replace(/,/g, "").replace(/'/g, ""); };// 从地址中获取经纬度 const getLatLong = (address) => {return fetch(`${address}&key=YOUR_API_KEY`).then((response) => response.json()).then((data) => {if (data.results.length > 0) {return {lat: data.results[0].geometry.location.lat,lng: data.results[0].geometry.location.lng,};} else {throw new Error("无法找到该地址的经纬度");}}); };// 在给定经纬度半径范围内查找汽车修理店 const findCarRepairShops = (lat, lng, radius) => {return fetch(`${lat},${lng}&radius=${radius}&type=car_repair&key=YOUR_API_KEY`).then((response) => response.json()) .then((data) => {return data.results;}); };// 在页面上显示结果 const displayResults = (results) => {const ul = document.getElementById("results").querySelector("ul");results.forEach((result) => {const li = document.createElement("li");const a = document.createElement("a");a.href = result.url;a.textContent = result.name;li.appendChild(a);ul.appendChild(li);}); };// 处理搜索表单提交 const handleSearchFormSubmit = (e) => {e.preventDefault();const location = document.getElementById("location").value;const formattedLocation = formatAddress(location);getLatLong(formattedLocation).then((latLong) => {return findCarRepairShops(latLong.lat, latLong.lng, 5000);}).then((results) => {displayResults(results);}).catch((error) => {alert(error.message);}); };// 绑定提交事件监听器到搜索表单 const searchForm = document.getElementById("search-form"); searchForm.addEventListener("submit", handleSearchFormSubmit);
版权声明

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