GEOJSON读写

最近有一些坐标数据需要采集和处理,了解到geojson是一种很好的地理信息保存格式,可以用来做文字数据和地理图层的中介,但是笔者没有发现比较好用的geojson工具,于是就自己动手写了一个。

class GeoJson():
    import json

    #基本模板
    Base={
        "type": "FeatureCollection",
        "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::3857" } },
        "features": [
            ]
        }

'''
如果生成的GEOJSON无法识别,请将"FeatureCollection"替换为"GeometryCollection","features"替换为"geometries"。
'''


    #定义参考系
    def __init__(self,crs={}):
        if crs is not  {}:
            self.Base.crs=crs


    #被打印的方法
    def __str__(self):
        return self.json.dumps(self.Base)

    #被迭代的方法
    def __iter__(self):
        return self.Base['features']

    #返回元素数量
    def __len__(self):
        return len(self.Base["features"])


    #保存JSON文件   
    def save(self,filename:str):
        with open(filename, mode='w',encoding='utf-8') as f:
            self.json.dump(self.Base,ensure_ascii=False, fp=f)

    #读取JSON文件
    def read(self,filename:str):
        with open(filename, mode='r',encoding='utf-8') as f:
            try:
                data=self.json.load(f)
                self.Base['features']=data['features']
                if 'crs' in data:
                    self.Base['crs']=data['crs']
            except :
                print('文件格式不正确,读取失败。')
            

    #添加要素,私有方法
    def __add(self,type:str,coordinates:list,properties={}):
        Feature={
                    "type":"Feature",
                    "properties":properties,
                    "geometry":{
                    "type":type,
                    "coordinates":coordinates
                    }
                }
        self.Base['features'].append(Feature)





    #添加点要素
    def addPoint(self,coordinates:list,properties={}):
        if len(coordinates)==2:
            self.__add('Point',coordinates,properties)
        
           

    #添加线要素       
    def addLineString(self,coordinates:list,properties={}):
        if len(coordinates)>=2:
            self.__add('LineString',coordinates,properties)

    #添加面要素
    def addPolygon(self,coordinates:list,properties={}):
        if len(coordinates)>=3:
            self.__add('Polygon',coordinates,properties)


    #合并图层
    def merge(self,another):
        try:
            for item in another:
                self.Base['features'].append(item)
                

        except: 
            print('合并图层失败')


    pass

测试:

a=GeoJson()
a.addPoint([11407147.964499999,3441733.3486000001],{'FID':0})

a.save('e.json')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

高堂明镜悲白发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值