跳转到内容
Tutorial

免费地理编码 API:一次 REST 调用中的正向、反向和距离

| 6 min read

将地址转换为坐标,将坐标转换为地址,并计算具有三个 REST 端点的点之间的距离。 免费套餐,无需 Google 地图。

Satellite view of city with map pins overlay
Photo by NASA on Unsplash

您的送货应用程序需要将街道地址转换为纬度和经度以进行路线选择。 Google 地图地理编码 API 每 1,000 个请求的费用为 5 美元。 对于一家进行 10,000 次送货的初创公司 一天,仅地理编码一项就需要 50 美元/天。

botoi geo API 涵盖正向地理编码、反向地理编码和距离计算 三个 REST 端点。 匿名访问每天可免费处理 100 个请求。 付费计划 起价 9 美元/月,覆盖平台中所有 150 多个端点,而不仅仅是地理编码。

正向地理编码:地址到坐标

/v1/geo/geocode 端点采用街道地址并返回纬度, 经度和标准化格式的地址。 一个 POST 请求:

curl -X POST https://api.botoi.com/v1/geo/geocode \\
  -H "Content-Type: application/json" \\
  -d '{"address": "1600 Amphitheatre Parkway, Mountain View, CA"}'

回复:

{
  "success": true,
  "data": {
    "latitude": 37.4224764,
    "longitude": -122.0842499,
    "formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
    "place_name": "Googleplex",
    "country": "United States",
    "country_code": "US"
  }
}

响应包括国家/地区代码、地名(如果可用)和 formatted_address 您可以存储为规范版本的字符串。 部分 也解决了工作问题; API 将“加利福尼亚州山景城”解析为市中心的坐标。

反向地理编码:坐标到地址

移动应用程序捕获 GPS 针掉落。 您需要一个人类可读的收据地址。 这 /v1/geo/reverse 端点获取纬度和经度并打破 结果转化为结构化组件:

curl -X POST https://api.botoi.com/v1/geo/reverse \\
  -H "Content-Type: application/json" \\
  -d '{"latitude": 37.4224, "longitude": -122.0842}'

回复:

{
  "success": true,
  "data": {
    "formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
    "street": "Amphitheatre Pkwy",
    "house_number": "1600",
    "city": "Mountain View",
    "state": "California",
    "postal_code": "94043",
    "country": "United States",
    "country_code": "US"
  }
}

每个字段都是分开的:街道、门牌号、城市、州、邮政编码和国家/地区。 您不需要解析单个字符串来提取城市或邮政编码。

两点之间的距离计算

/v1/geo/distance 端点计算之间的大圆距离 两个坐标对。 它返回公里和英里:

curl -X POST https://api.botoi.com/v1/geo/distance \\
  -H "Content-Type: application/json" \\
  -d '{"from": {"lat": 37.7749, "lng": -122.4194}, "to": {"lat": 34.0522, "lng": -118.2437}}'

回复:

{
  "success": true,
  "data": {
    "distance_km": 559.12,
    "distance_miles": 347.42,
    "from": { "lat": 37.7749, "lng": -122.4194 },
    "to": { "lat": 34.0522, "lng": -118.2437 }
  }
}

旧金山至洛杉矶:559 公里。 计算使用半正矢公式,其中 为您提供穿过地球表面的直线距离。 对于接近过滤器,交付 半径检查并存储定位器特征,这是正确的度量。

实际示例:结帐时的地址验证

一位顾客在结账表格中输入“123 Fake Street, Nowhereville”。 语法验证 通过,因为它看起来像一个地址。 地理编码解决了这个问题。 如果 API 不能 将地址解析为坐标,该地址可能无效。

async function validateAddress(address) {
  const res = await fetch("https://api.botoi.com/v1/geo/geocode", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Api-Key": process.env.BOTOI_API_KEY,
    },
    body: JSON.stringify({ address }),
  });

  const { success, data } = await res.json();

  if (!success || !data.latitude) {
    return { valid: false, suggestion: null };
  }

  return {
    valid: true,
    formatted: data.formatted_address,
    coordinates: {
      lat: data.latitude,
      lng: data.longitude,
    },
  };
}

// Usage in a checkout form handler
const result = await validateAddress("1600 Amphitheatre Parkway, Mountain View");

if (!result.valid) {
  // Show error: "We couldn't verify this address. Check for typos."
}

// Use result.formatted as the canonical address
// Use result.coordinates for delivery routing

这种方法可以在您之前捕获拼写错误、不存在的街道名称和不完整的地址 将包裹运送到任何地方。 这 formatted_address 字段给你 存储在数据库中的标准化版本。

实际示例:商店定位器

给定用户的坐标(来自浏览器地理位置或地理编码地址),找到三个 最近的商店:

async function findNearestStore(userLat, userLng, stores) {
  // Calculate distance from user to each store in parallel
  const distances = await Promise.all(
    stores.map(async (store) => {
      const res = await fetch("https://api.botoi.com/v1/geo/distance", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-Api-Key": process.env.BOTOI_API_KEY,
        },
        body: JSON.stringify({
          from: { lat: userLat, lng: userLng },
          to: { lat: store.lat, lng: store.lng },
        }),
      });

      const { data } = await res.json();
      return { ...store, distance_km: data.distance_km };
    })
  );

  // Sort by distance and return the closest 3
  return distances
    .sort((a, b) => a.distance_km - b.distance_km)
    .slice(0, 3);
}

const stores = [
  { name: "Downtown", lat: 37.7849, lng: -122.4094 },
  { name: "Mission Bay", lat: 37.7699, lng: -122.3894 },
  { name: "Sunset", lat: 37.7549, lng: -122.4894 },
];

const nearest = await findNearestStore(37.7749, -122.4194, stores);
// Returns stores sorted by distance from the user

对于少量商店(50 家以下),并行 API 调用效果很好。 对于数百个 位置,在客户端进行半正矢计算并仅使用 API 进行地理编码 步骤。

实例:配送半径检查

食品配送应用程序需要拒绝距离厨房 25 公里半径之外的订单。 检查 接受订单前的距离:

async function isWithinDeliveryRadius(
  warehouseLat, warehouseLng,
  customerLat, customerLng,
  maxRadiusKm
) {
  const res = await fetch("https://api.botoi.com/v1/geo/distance", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Api-Key": process.env.BOTOI_API_KEY,
    },
    body: JSON.stringify({
      from: { lat: warehouseLat, lng: warehouseLng },
      to: { lat: customerLat, lng: customerLng },
    }),
  });

  const { data } = await res.json();

  return {
    eligible: data.distance_km <= maxRadiusKm,
    distance_km: data.distance_km,
  };
}

// Check if a customer is within 25 km of the warehouse
const check = await isWithinDeliveryRadius(
  37.7749, -122.4194,  // warehouse
  37.3382, -121.8863,  // customer in San Jose
  25                    // 25 km radius
);

if (!check.eligible) {
  console.log(
    \`Customer is \\\${check.distance_km.toFixed(1)} km away. Outside delivery zone.\`
  );
}

该检查需要一次 API 调用,并在 100 毫秒内返回。 将其与正向地理编码相结合 在两个连续请求中从输入地址到交付资格决定。

要点

  • /v1/geo/geocode 将街道地址转换为纬度/经度 标准化格式的地址。 适用于部分地址和地名。
  • /v1/geo/reverse 将坐标转换为具有单独的结构化地址 街道、城市、州、邮政编码和国家/地区字段。
  • /v1/geo/distance 使用以下方法计算两点之间的大圆距离 半正矢公式。 返回公里和英里。
  • 匿名访问每分钟允许 5 个请求,每天允许 100 个请求。 无需 API 密钥 测试或小批量使用。
  • 所有三个端点都接受并返回 JSON。 没有查询字符串编码,没有 XML 解析,没有 SDK安装。 任何带有 HTTP 客户端的语言都可以。

FAQ

地理编码 API 是免费的吗?
匿名访问的速度为每分钟 5 个请求和每天 100 个请求,并具有基于 IP 的速率限制。 无需 API 密钥或帐户。 为了获得更高的吞吐量,付费计划起价为 9 美元/月,单个 API 密钥涵盖所有 150 多个端点。
正向地理编码和反向地理编码有什么区别?
正向地理编码将街道地址或地名转换为纬度和经度坐标。 反向地理编码的作用相反:它采用纬度和经度坐标并返回最近的街道地址。 botoi API 支持通过 /v1/geo/geocode 和 /v1/geo/reverse。
距离端点返回的是行驶距离还是直线距离?
/v1/geo/distance 端点使用半正弦公式返回两点之间的大圆(直线)距离。 它不考虑道路或驾驶路线。 对于输送半径检查和邻近过滤器,直线距离通常就足够了。
API 使用什么坐标系?
API 使用 WGS 84 (EPSG:4326),与 GPS 设备、Google 地图和 OpenStreetMap 使用的坐标系相同。 纬度范围为 -90 到 90,经度范围为 -180 到 180。
我可以使用地理编码 API 进行批量处理吗?
API 对每个请求处理一个地址或坐标对。 对于批量地理编码,并行发送多个请求。 在免费套餐中,您每分钟可以发送 5 个。 付费计划支持更高的并发性来处理数千个地址。

开始使用 botoi 构建

150+ 个 API 端点,涵盖查询、文本处理、图片生成和开发者工具。免费套餐,无需信用卡。