利用Python獲取全國GeoJSON數據並預覽轉換成shp格式文件

GeoPandas

GeoPandas是一個開源項目,Pandas是Python的一個結構化數據分析的利器,GeoPandas擴展了pandas使用的數據類型,允許對幾何類型進行空間操作,其DataFrame結構相當於GIS數據中的一張屬性表,使得可以直接操作矢量數據屬性表,其目標是使得在python中操作地理數據更方便。下面是具體步驟:

安裝GeoPandas庫

利用Anaconda3集成環境,所以就直接在cmd命令窗口執行conda install -c conda-forge geopandas。這句話會下載geopandas依賴的一些庫,安裝時間較長耐心等待就好。 ( 可以從清華大學鏡像下載Miniconda。地址是 https://mirrors.tuna.tsinghua.edu.cn/help/anaconda/),其他方式都比較複雜一點,網上也很全面,可以自行百度下載,不在細說。

GeoJSON基礎數據獲取
# -*- coding: utf-8 -*-

"""
@File    : JsonCrawlerLocal.py
@notice  : 將數據GeoJSON文件保存到本地
"""
# 數據下載地址
import json
import requests
import io


# 獲取所有數據json文件


def download_Json(url, name):
    print("-----------正在下載json文件 %s" % (url))
    try:
        # 將響應信息進行json格式化
        response = requests.get(url)
        versionInfo = response.text
        versionInfoPython = json.loads(versionInfo)

        # print(versionInfo)
        path = "./data/" + str(name) + ".json"
        # 將json格式化的數據保存
        with open(path, 'w', encoding='utf-8') as f1:
            f1.write(json.dumps(versionInfoPython, indent=4))
        print("下載成功,文件保存位置:" + path)
    except Exception as ex:
        print("--------下載出錯----")
        pass


# 數據下載地址
# http://datav.aliyun.com/tools/atlas/#&lat=33.521903996156105&lng=104.29849999999999&zoom=4
# 地名:中國|adcode:100000
# https://geo.datav.aliyun.com/areas/bound/100000.json
# 地名:河南省|adcode:410000
# https://geo.datav.aliyun.com/areas/bound/410000.json
# 地名:河南省+子區域|adcode:410000
# https://geo.datav.aliyun.com/areas/bound/410000_full.json
# 地名:江蘇省|adcode:320000
# https://geo.datav.aliyun.com/areas/bound/320000.json
# 地名:山東省|adcode:370000
# 地名:山東省|adcode:340000
# 地名:北京市ad|code:110000

# 獲取對應數據的json文件
url = 'https://geo.datav.aliyun.com/areas/bound/320500.json'#輸入json地址
download_Json(url, "蘇州")
#第一個參數是json文件的地址,第二個參數是文件保存的名稱,
GeoJSON數據展示
# -*- coding: utf-8 -*-

"""
@File    : MapDisplay.py
@notice  : 展示geojson生成的數據,並進行投影
"""

import geopandas
from shapely import geometry
import matplotlib.pyplot as plt

#保存在本地的geoJson數據
# data1 = geopandas.read_file('./data/河南.json')
data2 = geopandas.read_file('./data/江蘇.json')
# data3 = geopandas.read_file('./data/山東.json')
# data4 = geopandas.read_file('./data/安徽.json')

fig, ax = plt.subplots()
# data1.plot(ax=ax, color="#FDECD2",alpha=1)#透明樣式alpha=0.8
data2.plot(ax=ax, color="#FADCE8",alpha=0.8)
# data3.plot(ax=ax, color="#DFE2F3",alpha=0.9)
# data4.plot(ax=ax, color="#E0ECDF",alpha=0.7)
# 繪製bbox框示意,進行重點標記(可以進行註釋)
ax = geopandas.GeoSeries([geometry.box(minx=115,  #紅框經度(小)
                                      maxx=118,  # 紅框經度(大)
                                      miny=34,  #紅框緯度(小)
                                      maxy=36)##紅框緯度(大)
                        .boundary]).plot(ax=ax, color='red')
plt.savefig("./images/MapDisplayMoreProvince.png")#保存圖片到項目images路徑下
plt.show()
保存 GeoJSON數據爲shapefile到本地
# -*- coding: utf-8 -*-

"""
@File    : MapDisplay.py
@notice  : 將json生成的數據保存到本地
"""

import geopandas
import matplotlib.pyplot as plt


def saveShapefile(file_path, output_shapefile_name):
    try:
        data = geopandas.read_file('./data/' + str(file_path) + '.json')
        ax = data.plot()
        plt.show()  # 顯示生成的地圖
        localPath = 'output/' + str(output_shapefile_name)#用於存放生成的文件
        data.to_file(localPath, driver='ESRI Shapefile', encoding='utf-8')
        print("--保存成功,文件存放位置:"+localPath)
    except Exception as ex:
        print("--------JSON文件不存在,請檢查後重試!----")
        pass

#第一個參數是輸入爬取GeoJSON的名稱,
# 第二個參數是輸出shapfile的名稱(默認投影爲wgs1984)
saveShapefile('蘇州', '蘇州市')

小tips:
1.pip升級安裝 python -m pip install --upgrade pip -i https://pypi.douban.com/simple
2.python3.7安裝geopandas庫需要同時安裝gdal文件和Fiona文件,參考文章:
如果是下載的文件,需要指定具體路徑,如pip install C:\Users\Run\Downloads\pyHook-1.5.1-cp37-cp37m-win_amd64.whl
https://blog.csdn.net/micrasoft007/article/details/112652700
https://blog.csdn.net/weixin_38917807/article/details/81675233
3.爲python安裝matplotlib模塊:
matplotlib是python中強大的畫圖模塊。
首先確保已經安裝python,然後用pip來安裝matplotlib模塊。
進入到cmd窗口下,執行python -m pip install -U pip setuptools進行升級。
接着鍵入python -m pip install matplotlib進行自動的安裝,系統會自動下載安裝包。
安裝完成後,可以用python -m pip list查看本機的安裝的所有模塊,確保matplotlib已經安裝成功。
參考文章:https://www.cnblogs.com/-1307/p/6529269.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章