将google方向转换为shapefile行

时间:2017-02-03 21:22:56

标签: python json python-2.7 google-maps gis

是否可以从Google Directions API返回json,并将该信息转换为与路线折线相同的shapefile行?

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

1 个答案:

答案 0 :(得分:0)

我终于找到了如何使用FionaShapely以及我在GitHub上找到的function来修改以适应:

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文件包含来自Google maps API的json响应,并且与代码位于同一文件夹中。解码给定行程的折线,然后使用Shapely将其转换为LineString,然后使用Fiona将每个LineString保存到shapefile中。