
本教程旨在帮助您解决如何高效筛选指定城市列表的问题,特别是当您需要根据城市间的驾驶距离进行过滤时。我们将聚焦于一个具体场景:从一份德国城市列表中,筛选出与特定“主位置”(例如哈默尔恩,德国下萨克森州)驾驶距离在75公里以内(含)的所有城市。不同于手动网页抓取,本教程将引导您采用更专业、更稳定的api集成方案,以确保数据获取的准确性、稳定性和处理效率。
在处理地理位置数据时,许多开发者可能会首先想到通过网页抓取(Web Scraping)来获取所需信息。例如,用户最初尝试通过抓取 www.luftlinie.org 网站上的距离数据。然而,这种方法存在以下几个主要弊端:
因此,对于需要稳定、高效、可靠获取地理距离数据的应用场景,使用专业的地理距离API是更优的选择。
幸运的是,许多地理信息服务都提供了API接口。distance.to 就是其中之一,并且它在RapidAPI平台上提供了易于集成的API服务。通过使用API,您可以规避上述所有问题,直接获取结构化的距离数据。
在使用distance.to API之前,您需要完成以下准备工作:
distance.to API通常提供一个或多个端点来计算两点之间的距离。以计算驾驶距离为例,您可能需要使用一个类似于 /v1/route-summary 的端点,并提供起点和终点的地址信息。API响应通常是JSON格式,其中包含距离、时间等详细信息。
核心步骤:
以下是一个使用JavaScript(配合async/await和fetch)实现城市筛选的完整示例。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>城市距离筛选器</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
#results { margin-top: 20px; border: 1px solid #ccc; padding: 15px; min-height: 100px; }
ul { list-style-type: none; padding: 0; }
li { margin-bottom: 5px; }
.loading { color: gray; }
.error { color: red; }
</style>
</head>
<body>
<h1>德国城市驾驶距离筛选</h1>
<p>筛选出与主位置“哈默尔恩, 下萨克森州, 德国”驾驶距离在75公里以内(含)的城市。</p>
<button id="filterButton">开始筛选</button>
<div id="results">
<p class="loading">点击“开始筛选”按钮以获取结果...</p>
</div>
<script>
// 请替换为您的RapidAPI密钥和主机
const RAPIDAPI_KEY = "YOUR_RAPIDAPI_KEY";
const RAPIDAPI_HOST = "distance-to.p.rapidapi.com"; // 根据RapidAPI文档获取
const mainPosition = "Hameln,Niedersachsen,DEU"; // 主位置
const maxDistanceKm = 75; // 最大允许距离(公里)
// 待筛选的德国城市列表
const germanCities = [
"Bad Eilsen", "Buchholz", "Hannover", "Heeßen", "Luhden", "Samtgemeinde Lindhorst",
"Beckedorf", "Heuerßen", "Berlin", "Lindhorst", "Lüdersfeld", "Samtgemeinde Nenndorf",
"Bad Nenndorf", "Haste", "Kassel", "Hohnhorst", "Suthfeld", "Samtgemeinde Niedernwöhren",
"Lauenhagen", "Meerbeck", "Dortmund", "Niedernwöhren", "Nordsehl", "Pollhagen",
"Wiedensahl", "Samtgemeinde Nienstädt", "Helpsen", "Hespe", "Frankfurt", "Nienstädt",
"Freiburg", "Seggebruch", "Potsdam"
];
const resultsDiv = document.getElementById('results');
const filterButton = document.getElementById('filterButton');
/**
* 调用distance.to API获取两点间的驾驶距离
* @param {string} from 起点城市
* @param {string} to 终点城市
* @returns {Promise<number|null>} 驾驶距离(公里)或null(如果发生错误)
*/
async function getDrivingDistance(from, to) {
// 确保城市名称在URL中正确编码
const fromEncoded = encodeURIComponent(from + ",Niedersachsen,DEU"); // 假设所有城市都在下萨克森州,可根据实际情况调整
const toEncoded = encodeURIComponent(to + ",Niedersachsen,DEU");
// 构建API请求URL
// 注意:具体的API端点和参数可能需要根据distance.to在RapidAPI上的文档进行调整
const url = `https://${RAPIDAPI_HOST}/v1/route-summary?from=${fromEncoded}&to=${toEncoded}`;
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': RAPIDAPI_KEY,
'X-RapidAPI-Host': RAPIDAPI_HOST
}
};
try {
const response = await fetch(url, options);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
}
const data = await response.json();
// 假设API响应结构中,驾驶距离在data.route.distance.value,单位为公里
// 请务必根据实际API文档确认此路径
if (data && data.route && data.route.distance && typeof data.route.distance.value === 'number') {
return data.route.distance.value; // 返回公里数
} else {
console.warn(`无法从API响应中解析距离,城市: ${to}`, data);
return null;
}
} catch (error) {
console.error(`获取 ${from} 到 ${to} 的距离时发生错误:`, error);
return null;
}
}
/**
* 筛选城市并显示结果
*/
async function filterCities() {
resultsDiv.innerHTML = '<p class="loading">正在获取距离并筛选城市,请稍候...</p>';
filterButton.disabled = true;
const filteredCities = [];
const promises = germanCities.map(async city => {
const distance = await getDrivingDistance(mainPosition, city);
if (distance !== null && distance <= maxDistanceKm) {
filteredCities.push({ name: city, distance: distance });
}
});
// 等待所有API请求完成
await Promise.all(promises);
// 排序(可选):按距离从小到大
filteredCities.sort((a, b) => a.distance - b.distance);
// 显示结果
if (filteredCities.length > 0) {
let html = '<h2>符合条件的城市列表:</h2><ul>';
filteredCities.forEach(city => {
html += `<li>${city.name} (距离: ${city.distance.toFixed(2)} 公里)</li>`;
});
html += '</ul>';
resultsDiv.innerHTML = html;
} else {
resultsDiv.innerHTML = '<p>没有找到符合条件的城市。</p>';
}
filterButton.disabled = false;
}
filterButton.addEventListener('click', filterCities);
// 初始加载时可以自动触发一次,或者等待用户点击
// filterCities();
</script>
</body>
</html>代码说明:
通过本教程,您应该已经掌握了如何利用专业的地理距离API(如RapidAPI上的distance.to)来高效、稳定地筛选城市列表。相比于传统的网页抓取,API集成方案提供了更高的可靠性、更快的响应速度和更好的可维护性。记住,在实际项目中,始终优先考虑使用官方提供的API接口,并注意API密钥安全、限额管理和完善的错误处理机制。
以上就是使用API高效筛选城市列表:基于驾驶距离的地理数据处理教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号