首页 > 解决方案 > 我应该如何在静态图像 api 的 URL 中添加 geojson?

问题描述

我有这个geojson(所有这些代码都在python中)

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties":  {
        "stroke": "#000000",
        "fill": "#005776",
        "fill-opacity": 1.0
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [-81.26581704096897, 28.37974376331988],
            [-81.26601725837781, 28.37977498699149],
            [-81.26613780689904, 28.37940694447166],
            [-81.26594365491499, 28.3793572200485],
            [-81.26581704096897, 28.37974376331988]
          ]
        ]
      }
    }
  ]
}

我是这样编码的:

geojson_string = json.dumps(geojson, separators=(',', ':'))
geojson_encoded = urllib.parse.quote(f"{{{geojson_string}}}")

并得到这个字符串:

%7B%22type%22%3A%22FeatureCollection%22%2C%22features%22%3A%5B%7B%22type%22%3A%22Feature%22%2C%22properties%22%3A%7B%22stroke%22%3A%22%23000000%22%2C%22fill%22%3A%22%23005776%22%2C%22fill-opacity%22%3A1%7D%2C%22geometry%22%3A%7B%22type%22%3A%22Polygon%22%2C%22coordinates%22%3A%5B%5B%5B-81.26581704096897%2C28.37974376331988%5D%2C%5B-81.26601725837781%2C28.37977498699149%5D%2C%5B-81.26613780689904%2C28.37940694447166%5D%2C%5B-81.26594365491499%2C28.3793572200485%5D%2C%5B-81.26581704096897%2C28.37974376331988%5D%5D%5D%7D%7D%7D

然后我正在制作这样的网址:

url = f"https://api.mapbox.com/styles/v1/{user}/{style}/static/geojson(geojson_encoded)/auto/640x360?{access_token}"

但我收到此错误:

message: "Failed parsing geojson"

有人可以帮助我知道我做错了什么吗?

标签: pythonmapboxgeojson

解决方案


问题似乎在于您的 Python 代码如何对 API 进行编码和/或发出请求,因此我建议您仔细检查发出的请求是否符合您的预期。

如果我采用您未编码的 geojson 对象,并将其直接包含在 cURL 请求中(确保仅对必要的禁止使用#颜色进行编码),那么我在收到有效响应时没有任何问题:

https://api.mapbox.com/styles/v1/mapbox/light-v10/static/geojson({"type":"FeatureCollection","features":[{"type":"Feature","properties":{"stroke":"%23000000","fill":"%23005776","fill-opacity":1},"geometry":{"type": "Polygon","coordinates":[[[-81.26581704096897,28.37974376331988],[-81.26601725837781,28.37977498699149],[-81.26613780689904,28.37940694447166],[-81.26594365491499,28.3793572200485],[-81.26581704096897,28.37974376331988]]]}}]})/auto/630x360?access_token=my.token

上述请求以您想要的图像响应(尽管没有自定义用户样式):

以多边形为中心的静态地图图像


⚠️ 免责声明:我目前为 Mapbox 工作⚠️


推荐阅读