python对象转geojson,geojson转shp文件

一、python对象转geojson

工作中遇到需要把经纬度坐标在地图上进行可视化,需要写成geojson格式的文件。笔记记录一下学习过程。

import pandas
import geojson

path = r'关联场站的公交首末站.xlsx'


def convert_point_string2_list(point_string):
    point_list = []
    point_arr = str(point_string).split(';')
    for point in point_arr:
        tmp = point.split(',')
        if len(tmp) == 2:
            point_list.append([float(tmp[0]), float(tmp[1])])
    return point_list


data_f = pandas.read_excel(path)
#把每一行数据中的点和多边形转换成geojson的对象
feat_list = []
for item in data_f.values:
	'''
    item[0]:站点名称
    item[1]:经纬度字符串
    item[2]:公交线路
    item[3]:场站名称
    item[4]:站点距离场站的步行距离
    item[5]:场站的功能
    item[6]:场站的面积
    item[7]:场站的url 
    item[8]:场站的轮廓
    '''
    print(item)
    point_string = item[1]
    point_arr = str(item[1]).replace(';', '').split(',')
    point = geojson.Point((float(point_arr[0]), float(point_arr[1])))
    properties_point = {'name': str(item[0]), 'way_line': str(item[2])}
    point_feature = geojson.Feature(geometry=point, properties=properties_point)
    feat_list.append(point_feature)
    coords = convert_point_string2_list(item[8])
    if len(coords) == 0:
        continue
    polygon = geojson.Polygon([coords])
    properties_poly = {'name': str(item[3]), 'distance': str(item[4]),'fun':str(item[5]),'area':str(item[6])}
    polygon_feature = geojson.Feature(geometry=polygon, properties=properties_poly)
    feat_list.append(polygon_feature)
feat_collection = geojson.FeatureCollection(feat_list)
geojson_str = geojson.dumps(feat_collection)
print(geojson_str)
with open("output.geojson", "w") as f:
    geojson.dump(feat_collection, f)

生成的geojosn文件可以在https://wandergis.com/geojson.io/#map=14/24.4792/118.1462
中地图展示

二、geojson转shp文件

如果需要把地图对象在ArcMap中展示,就需要转换成shp文件

import geopandas as gpd
import shapefile

# 读取GeoJSON文件并创建GeoDataFrame
gdf = gpd.read_file('output.geojson')

# 按照点和多边形进行分组
point_gdf = gdf[gdf.geometry.type == 'Point']
polygon_gdf = gdf[gdf.geometry.type == 'Polygon']

# 创建shapefile文件并写入点图层(写入指定的字段)
w = shapefile.Writer('output',encoding='utf-8')
w.autoBalance = 1
w.field('name')
w.field('way_line')
for i in range(len(point_gdf)):
    w.point(point_gdf.iloc[i].geometry.x, point_gdf.iloc[i].geometry.y)
    w.record(point_gdf.iloc[i][0],point_gdf.iloc[i][1])
w.close()

# 写入点图层
# point_gdf.to_file('output.shp',encoding='utf-8')

# 写入多边形图层(写入所有的字段)
polygon_gdf.to_file('output1.shp',encoding='utf-8')