【问题标题】:Converting MSSQL database to GeoJSON format将 MSSQL 数据库转换为 GeoJSON 格式
【发布时间】:2021-03-12 11:43:38
【问题描述】:

我正在尝试使用 Python 访问 MSSQL 数据库,然后将结果写入 GeoJSON 文件。 到目前为止,我有这段代码,但我无法获得将文件保存到我的目录的工作端部分

import pandas as pd
import pyodbc
import geojson
import json
from geojson import Feature, FeatureCollection, Point


conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=LAPTOP;'
                      'Database=WB;'
                      'Trusted_Connection=yes;')


sql_query = pd.read_sql_query(''' 
                              select * from WB.dbo.Transactions
                              '''
                              ,conn) # here, the 'conn' is the variable that contains your database connection information from step 2

df = pd.DataFrame(sql_query)
def df_to_geojson(df, properties, lat='latitude', lon='longitude'):
    geojson = {'type':'FeatureCollection', 'features':[]}
    for _, row in df.iterrows():
        feature = {'type':'Feature',
                   'properties':{},
                   'geometry':{'type':'Point',
                               'coordinates':[]}}
        feature['geometry']['coordinates'] = [row[lon],row[lat]]
        for prop in properties:
            feature['properties'][prop] = row[prop]
        geojson['features'].append(feature)
    return geojson

我尝试了以下方法将其保存到输出文件中,但它抛出了一个错误,即 GeoJSON 是一个模块而不是一个字符串 - 所以我将上面的代码从 geojson 更改为 geojson1 然后它出现了 geojson1 是'未定义

with open('C:/Users/Public/Documents/transactions.geojson', 'w') as f:
    f.write(geojson)

【问题讨论】:

    标签: python sql pandas geojson


    【解决方案1】:

    在将 json.dump(geojson) 写入文件之前尝试添加它。 此外,您不应在第 3 行和第 5 行两次导入模块。

    【讨论】:

    • 好的,我明白了。您是否尝试再添加一行。调用 result_json = df_to_geojson(df) 之类的函数,并在写入中使用 result_json。
    • 缩进是我的问题,向 Tobias 道歉。所以文件现在在那里但什么都不包含 - 我很困惑为什么它是空白的,因为我已经说明了如何解析它
    猜你喜欢
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 2018-11-29
    相关资源
    最近更新 更多