地理编码时如何同时获取城市名称?

How to also get the name of the city when geocoding?

我正在使用 Mapbox Geocoding API 查找用户输入提供的地点的纬度和经度。这很好用。我还想显示位于此位置的城市名称。

这是一个示例请求,它搜索德国的邮政编码“70176”:

https://api.mapbox.com/geocoding/v5/mapbox.places/70176.json?fuzzyMatch=true&language=en&access_token=redacted

这是答案:

{
   "type":"FeatureCollection",
   "query":[
      "70176"
   ],
   "features":[
      {
         "id":"postcode.12480061547829920",
         "type":"Feature",
         "place_type":[
            "postcode"
         ],
         "relevance":1,
         "properties":{

         },
         "text_en":"70176",
         "place_name_en":"70176, Stuttgart, Baden-Württemberg, Germany",
         "text":"70176",
         "place_name":"70176, Stuttgart, Baden-Württemberg, Germany",

   [...]

}

如您所见,它确实提供了包含城市 ("Stuttgart") 的完整地址,但并未分开。您可以通过在查询中包含 &types=place 来指定您只查找城市,但它也只接受城市名称作为输入。

如何在不进行两次 API 调用的情况下获取纬度、经度和城市名称?

您实际上从您提出的请求中获得了所有这些信息:

边界框的中心坐标,将城市装箱在特征JSON对象的"center"项中返回。您从要素对象的 "place_name" 项中获取的城市名称。您必须解析字符串并用逗号分隔,然后 select 返回数组的第二项以获取城市名称。

{
"type": "FeatureCollection",
"query": [
    "70176"
],
"features": [
    {
        "id": "postcode.12480061547829920",
        "type": "Feature",
        "place_type": [
            "postcode"
        ],
        "relevance": 1,
        "properties": {},
        "text_en": "70176",
        "place_name_en": "70176, Stuttgart, Baden-Württemberg, Germany",
        "text": "70176",
        "place_name": "70176, Stuttgart, Baden-Württemberg, Germany",
        "bbox": [
            9.155781,
            48.77099,
            9.169018,
            48.784448
        ],
        "center": [
            9.16,
            48.78
        ],
        "geometry": {
            "type": "Point",
            "coordinates": [
                9.16,
                48.78
            ]
        },
        "context": [
            {
                "id": "place.5443458428087800",
                "wikidata": "Q1022",
                "text_en": "Stuttgart",
                "language_en": "en",
                "text": "Stuttgart",
                "language": "en"
            },
            {
                "id": "region.10788925313210430",
                "short_code": "DE-BW",
                "wikidata": "Q985",
                "text_en": "Baden-Württemberg",
                "language_en": "en",
                "text": "Baden-Württemberg",
                "language": "en"
            },
            {
                "id": "country.10743216036480410",
                "short_code": "de",
                "wikidata": "Q183",
                "text_en": "Germany",
                "language_en": "en",
                "text": "Germany",
                "language": "en"
            }
        ]
    },