Python 将google方向转换为形状文件线

Python 将google方向转换为形状文件线,python,json,python-2.7,google-maps,gis,Python,Json,Python 2.7,Google Maps,Gis,是否可以获取从Google directions API返回的json并将该信息转换为与路由的多段线相同的shapefile线 我想在我正在QGIS中制作的地图上绘制一次旅行。我终于想出了如何使用和在GitHub上找到并修改以适应: import json import fiona import pandas as pd from shapely.geometry import LineString, mapping def decode_polyline(polyline_str):

是否可以获取从Google directions API返回的json并将该信息转换为与路由的多段线相同的shapefile线


我想在我正在QGIS中制作的地图上绘制一次旅行。

我终于想出了如何使用和在GitHub上找到并修改以适应:

import json
import fiona
import pandas as pd
from shapely.geometry import LineString, mapping

def decode_polyline(polyline_str):
    '''Pass a Google Maps encoded polyline string; returns list of lat/lon pairs'''
    index, lat, lng = 0, 0, 0
    coordinates = []
    changes = {'latitude': 0, 'longitude': 0}

    # Coordinates have variable length when encoded, so just keep
    # track of whether we've hit the end of the string. In each
    # while loop iteration, a single coordinate is decoded.
    while index < len(polyline_str):
        # Gather lat/lon changes, store them in a dictionary to apply them later
        for unit in ['latitude', 'longitude']: 
            shift, result = 0, 0

            while True:
                byte = ord(polyline_str[index]) - 63
                index+=1
                result |= (byte & 0x1f) << shift
                shift += 5
                if not byte >= 0x20:
                    break

            if (result & 1):
                changes[unit] = ~(result >> 1)
            else:
                changes[unit] = (result >> 1)

        lat += changes['latitude']
        lng += changes['longitude']

        coordinates.append((lng / 100000.0, lat / 100000.0))

    return coordinates

def get_linestring(trip_name):
    with open(trip_name + '.json', 'r') as data_file:    
        data = json.load(data_file, encoding='ISO-8859-1')

    the_points = []
    for step in data['routes'][0]['legs'][0]['steps']:
        the_points += decode_polyline(step['polyline']['points'])

    return LineString(the_points)


if __name__ == '__main__':
    trip_names = ['trip1', 'trip2', 'trip3']

    driver = 'ESRI Shapefile'
    crs = {'no_defs': True, 
            'ellps': 'WGS84', 
            'datum': 'WGS84', 
            'proj': 'longlat'}
    schema = {'geometry': 'LineString', 'properties': {'route': 'str'}}
    with fiona.open('all_trips.shp', 'w', driver=driver, crs=crs, schema=schema) as layer:
        for trip_name in trip_names:
            layer.write({'geometry': mapping(get_linestring(trip_name)),
                            'properties': {'route': trip_name}
                            })
导入json
导入菲奥娜
作为pd进口熊猫
从shapely.geometry导入线字符串,映射
def解码多段线(多段线):
''传递谷歌地图编码的多段线字符串;返回lat/lon对“”的列表
指数,纬度,液化天然气=0,0,0
坐标=[]
更改={‘纬度’:0,‘经度’:0}
#坐标在编码时具有可变长度,所以只需保留
#追踪我们是否已经到达终点。各
#循环迭代时,对单个坐标进行解码。
当索引>1)
其他:
更改[单位]=(结果>>1)
纬度+=变化['纬度']
液化天然气+=变化['经度']
附加坐标((lng/100000.0,lat/100000.0))
返回坐标
def get_行字符串(行程名称):
打开(trip_name+'.json',r')作为数据_文件:
data=json.load(数据文件,编码='ISO-8859-1')
_点=[]
对于步进数据['routes'][0]['legs'][0]['steps']:
_点+=解码_多段线(步骤['polyline']['points'])
返回行字符串(_点)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
trip_name=['trip1','trip2','trip3']
驱动程序='ESRI Shapefile'
crs={'no_defs':正确,
‘ellps’:‘WGS84’,
“基准”:WGS84,
'proj':'longlat'}
schema={'geometry':'LineString','properties':{'route':'str'}
用菲奥娜打开(AulthRIP.SIP),“W”,驱动程序=驱动程序,CRS=CRS,Schema=Schema)作为层:
对于trip_名称中的trip_名称:
write({'geometry':映射(get_linestring(trip_name)),
'properties':{'route':trip_name}
})
代码假定
json
文件包含来自googlemapsapi的
json
响应,并且与代码位于同一文件夹中。对给定行程的折线进行解码,然后使用Shauly转换成<代码> LineString < /代码>,然后使用菲奥娜将每个<代码> LineString < /代码>保存到ShafFEFLE中。< /P>