Mapbox 地理编码时,如何获得城市名称?
我使用查找用户输入提供的地点的纬度和经度。这很有效。我还想显示这个位置的城市名称 这是一个示例请求,搜索德国邮政编码“70176”:Mapbox 地理编码时,如何获得城市名称?,mapbox,geocoding,Mapbox,Geocoding,我使用查找用户输入提供的地点的纬度和经度。这很有效。我还想显示这个位置的城市名称 这是一个示例请求,搜索德国邮政编码“70176”: https://api.mapbox.com/geocoding/v5/mapbox.places/70176.json?fuzzyMatch=true&language=en&access_token=redacted 答案是: { "type":"FeatureCollection", "query":[ "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",
[...]
}
正如你所见,它确实提供了完整的地址,其中包括城市(“斯图加特”),但它没有分开。您可以通过在查询中包含&types=place
来指定只查找城市,但它也只接受城市名称作为输入
如何在不进行两次API调用的情况下获取纬度、经度和城市名称?您实际上从请求中获得了所有这些信息: 在features JSON对象的“center”项中返回边界框的中心坐标和城市坐标。从要素对象的“地点名称”项中获取的城市名称。您必须解析字符串并用逗号将其拆分,然后选择返回数组的第二项以获取城市名称
{
"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"
}
]
},
如果真的那么容易。。。根据查询的不同,城市名称有时是第一个或第三个位置名称。使用“context”子JSON对象的“text”如何,其中“id”以位置开头?这似乎是独一无二的。我也试过,但它是一样的。城市并不总是第一个孩子。这不重要,它的位置是什么。只需循环遍历上下文JSON对象,并查找具有以“place”开头的“id”值的对象。好主意!不幸的是,它并不总是存在。比如“莫斯科”。