"""示例 3:按矩形范围 + 按条件表达式查询实体要素。 用法: python 03_query_features.py [mapid] [version] """ from __future__ import annotations import json import sys from _common import make_client, sample_mapid, sample_version def main() -> None: svc = make_client() mapid = sys.argv[1] if len(sys.argv) > 1 else sample_mapid() version = sys.argv[2] if len(sys.argv) > 2 else sample_version() print(f"[1/3] 读取 bounds") meta = svc.metadata(mapid, version=version) bounds_raw = meta["bounds"] print(" bounds =", bounds_raw) if isinstance(bounds_raw, str): nums = [float(v) for v in bounds_raw.strip().lstrip("[").rstrip("]").split(",")] elif isinstance(bounds_raw, (list, tuple)): nums = [float(v) for v in bounds_raw] elif isinstance(bounds_raw, dict): nums = [bounds_raw["min"]["x"], bounds_raw["min"]["y"], bounds_raw["max"]["x"], bounds_raw["max"]["y"]] else: raise RuntimeError(f"unknown bounds type: {type(bounds_raw)}") x1, y1, x2, y2 = nums # 要素里没有图层名字段——只有 layerindex;名字要查 metadata.layers(每项 {"index","name",...}) layers_raw = meta.get("layers") or [] layers = json.loads(layers_raw) if isinstance(layers_raw, str) else layers_raw layer_name = {l.get("index"): l.get("name") for l in layers} print(f"[2/3] 按矩形查实体(querytype=rect, limit=10)") bbox_feat = svc.query_features( querytype="rect", mapid=mapid, version=version, x1=x1, y1=y1, x2=x2, y2=y2, limit=10, fields="name,objectid,layerindex", ) result = bbox_feat.get("result", {}) if isinstance(bbox_feat.get("result"), dict) else {} features = result.get("features") or bbox_feat.get("result") or [] if isinstance(features, list) and features: print(" matched:", len(features), "features") print(" first:", json.dumps(features[0], ensure_ascii=False)[:300]) else: print(" (no features in this bounds)") print(f"[3/3] 按条件查实体(querytype=condition)") cond_feat = svc.query_features( querytype="condition", mapid=mapid, version=version, condition="name<>''", limit=5, fields="name,objectid,layerindex", ) cresult = cond_feat.get("result") if isinstance(cresult, list): # result 里每项是扁平字段对象(不是 GeoJSON properties 包裹) for f in cresult[:3]: print(" -", (f or {}).get("name"), "| layer=", layer_name.get((f or {}).get("layerindex"), "?")) else: print(" response:", json.dumps(cond_feat, ensure_ascii=False)[:300]) if __name__ == "__main__": main()