首页 > 编程语言 >Python下载openstreet map数据,解析路网并绘制CAD

Python下载openstreet map数据,解析路网并绘制CAD

时间:2022-11-08 19:23:26浏览次数:48  
标签:map openstreet Python writelevel print line txt road data2

利用Python完成某一城市的CAD路网数据

需要进一步优化

import re
import time

import requests
from xpinyin import Pinyin


def getCityRpadDataByOSM(cityName):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
        "Content-Type": "application/x-www-form-urlencoded"}
    data = '<osm-script><query type="relation"><has-kv k="boundary" v="administrative"/><has-kv k="name:zh" v="' + cityName + '"/></query><print/></osm-script>'
    url = "http://www.overpass-api.de/api/interpreter"
    response = requests.post(url, data=data.encode(), headers=headers)
    # 利用正则表达式提取 id
    match = re.search('<relation id="(.*?)">', response.text)
    id = match.group(1)
    # id 需要 10位
    if id:
        id = str(3600000000 + int(id))
        print('城市id:', id)
    else:
        return
    data2 = '<osm-script timeout="1800" element-limit="100000000"><union><area-query ref="' + id + '"/><recurse type="node-relation" into="rels"/><recurse type="node-way"/><recurse type="way-relation"/></union><union><item/><recurse type="way-node"/></union><print mode="body"/></osm-script>'
    response2 = requests.post(url, data=data2, headers=headers)
    if len(response2.text) > 1000:
        # 这里设置阀值是因为 网络问题会导致出现超时,丢掉这个包
        p = Pinyin()
        cityname = p.get_pinyin(cityName)
        with open(cityname + ".osm", "w", encoding='utf-8') as f:
            f.write(response2.text)


# print('第一步:爬取指定城市路网')
# print('输入城市名称,请写全称:')
# city = str(input())
city = '青岛市'
p = Pinyin()
cityname = str(p.get_pinyin(city))

# getCityRpadDataByOSM(cityName=city)
print('已获取到osm文件')
print('等待5s...')
time.sleep(5)
print('第二步:路网数据解析')
import osm2gmns as og

net = og.getNetFromOSMFile(cityname + '.osm')
og.outputNetToCSV(net, output_folder='output')
print('线形节点文件在output文件夹')
# print('道路等级和编号如下:'
#       '1:高速公路'
#       '2:国道/一级公路'
#       '3:省道'
#       '4:县道'
#       '5:乡道')
# print('请输入所需要的路网等级,如果需要全部,请输入0')
# num = int(input())
import pandas as pd

data = pd.read_csv('output/link.csv', encoding='GBK')
df = pd.DataFrame(data)
df1 = df['name']
df2 = df['link_type_name']
df3 = df['geometry'].str.replace('LINESTRING ', '')
df0 = [df1, df2, df3]
con = pd.concat(df0, axis=1)

con.to_csv('temp.csv', index=False)
data2 = pd.read_csv(r'temp.csv')

highway = data2[data2['link_type_name'] == 'motorway']  # 高速
wayG = data2[data2['link_type_name'] == 'trunk']  # 国道
wayS = data2[data2['link_type_name'] == 'primary']  # 省道
wayX = data2[data2['link_type_name'] == 'secondary']  # 县道
wayY = data2[data2['link_type_name'] == 'tertiary']  # 乡道


# coding:utf-8

def arr(inroad, outroad):
    with open('temp.txt', 'w') as f:
        f.truncate(0)
        f.close()
    with open('temp2.txt', 'w') as f:
        f.truncate(0)
        f.close()

    file1 = open(inroad, 'r', encoding='utf-8')  # 打开要去掉空行的文件
    file2 = open('temp.txt', 'w', encoding='utf-8')  # 生成没有空行的文件
    for line in file1.readlines():
        if line == '\n':
            line = line.strip('\n')
        file2.write(line)

    file1.close()
    file2.close()

    for line in open("temp.txt"):
        l2 = line.replace(", ", ";")
        l3 = l2.replace(" ", ",")
        l4 = l3.replace(";", ",0,")
        l5 = l4.replace('"(', "")
        l6 = l5.replace(')"', ",0")
        print(l6)
        with open('temp2.txt', 'a+') as gd:
            print(l6, file=gd)
            gd.close()

    file1 = open('temp2.txt', 'r', encoding='utf-8')  # 打开要去掉空行的文件
    file2 = open(outroad, 'w', encoding='utf-8')  # 生成没有空行的文件
    for line in file1.readlines():
        if line == '\n':
            line = line.strip('\n')
        file2.write(line)

    file1.close()
    file2.close()
    import os
    os.remove('temp2.txt')
    os.remove('temp.txt')


def writelevel(level, lname):
    level['geometry'].to_csv('output/' + lname + '.txt', index=False, index_label=False, header=False)
    arr('output/' + lname + '.txt', 'output/' + lname + '_final.txt')


writelevel(highway, 'highway')
writelevel(wayG, 'G_road')
writelevel(wayS, 'S_road')
writelevel(wayX, 'X_road')
writelevel(wayY, 'Y_road')
#
# if num == 1:
#     writelevel(highway, 'highway')
# elif num == 2:
#     writelevel(wayG, 'G_road')
# elif num == 3:
#     writelevel(wayS, 'S_road')
# elif num == 4:
#     writelevel(wayX, 'X_road')
# elif num == 5:
#     writelevel(wayY, 'Y_road')
# else:
#     print('编号输入错误,默认全部生成')
#     writelevel(highway, 'highway')
#     writelevel(wayG, 'G_road')
#     writelevel(wayS, 'S_road')
#     writelevel(wayX, 'X_road')
#     writelevel(wayY, 'Y_road')
import os

os.remove('temp.csv')
print('绘制CAD图,在开始之前,请打开CAD,然后按任意键继续')
print(input())
# !/usr/bin/env python
# -*- coding: utf-8 -*-

"""
    =============================
    Author: DalNur
    Email: [email protected]
    =============================
"""
import time

import pythoncom
import win32com.client

wincad = win32com.client.Dispatch("AutoCAD.Application")
doc = wincad.ActiveDocument
doc.Utility.Prompt("Hello! Autocad from pywin32com.\n")
msp = doc.ModelSpace
print(doc.Name)


def vtpnt(x, y, z=0):
    return win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R8, (x, y, z))


def vtobj(obj):
    return win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_DISPATCH, obj)


def vtfloat(lst):
    return win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R8, lst)


#
def g(pnts, r, g, b):
    points = vtfloat(pnts)
    plineObj = msp.AddPolyline(points)
    version = wincad.Application.Version[:2]  # 当前CAD的版本号
    clr = wincad.Application.GetInterfaceObject("AutoCAD.AcCmColor.%s" % version)
    clr.SetRGB(r, g, b)  # 创建红色
    doc.preferences.LineweightDisplay = 1
    plineObj.TrueColor = clr
    doc.Application.Update()


def impf(filename, R, G, B):
    with open(filename, 'r') as f:
        my_data = f.readlines()
        for line in my_data:
            line_data = line.split()
            s = [float(i) for i in line_data[0].split(',')]
            print(s)
            g(s, R, G, B)
            time.sleep(0.1)


impf('output/highway_final.txt', 255, 0, 0)
impf('output/G_road_final.txt', 0, 255, 0)
impf('output/S_road_final.txt', 0, 0, 255)
impf('output/X_road_final.txt', 0, 255, 255)
impf('output/Y_road_final.txt', 255, 0, 255)

标签:map,openstreet,Python,writelevel,print,line,txt,road,data2
From: https://www.cnblogs.com/agonygone/p/16870872.html

相关文章

  • python 中 lambda函数
     Lambda函数用于创建匿名函数:001、>>>add1=lambdax:x+2>>>add1(100)102>>>add1(50)52 >>>abc=lambdax:x*2>>>abc(10)20>>>abc(0.8)1.6......
  • python 中 format函数
     001、格式化数值>>>"{:.2%}".format(0.123456789)'12.35%'>>>"{:.5%}".format(0.123456789)'12.34568%'>>>"{:.2}".format(0.123456789)'0.12'>>>"{:.5}&quo......
  • HashMap面试题(一)
    HashMap面试题目录HashMap面试题一、HashMap扩容机制原理1、JDK1.7版本扩容机制JDK1.7resize方法源码initHashSeedAsNeeded()方法源码2、JDK1.8版本扩容机制方法执行流程......
  • python 中any 和 all函数
     001、 any只要一个结果为真,结果就为真>>>any([False,False,True])True>>>any([False,False,False])False  002、all只有所有结果为真才为真>>>......
  • Python程序调试分析大杀器--pystack-debugger
    分析程序异常某个进程100%,分析思路示例代码#-*-coding:utf8-*-importtimedeftest_1():a=1+1time.sleep(100*10)returnaif__name__=="__m......
  • python学习计划
    作为一个软件测试工程师,只会功能测试是走不远的,最直观的体现就是薪资上不去。虽然测试行业有着各种各样的新技术和辅助工具,但我一直认为学会一门编程语言才是最基础的东西,......
  • python中数值处理函数
     001、abs函数取绝对值>>>abs(100)100>>>abs(-500)500  002、round函数取小数点位数>>>round(99.95)##默认没有小数点100>>>roun......
  • Python中10个常见的安全漏洞及修复方法
    编写安全的代码很困难,当你学习一门编程语言、一个模块或框架时,你会学习其使用方法。在考虑安全性时,你需要考虑如何避免代码被滥用,Python也不例外,即使在标准库中,也存在着许多......
  • python(面向对象之元类,魔法方法)
    今日内容概要面向对象的魔法方法基于魔法方法的笔试题元类简介创建类的两种方式元类定制类的产生行为元类定制对象的产生行为魔法之__new__方法设计模式简介及单......
  • Python 生成MySQL数据库的表结构到word文档
    原理:读取系统表的数据,调用python-docx库生成word文档。importpymysqlfromdocximportDocumentfromdocx.sharedimportInchesdocument=Document()document.a......