2017-02-03 60 views

回答

0

我終於想通了如何使用FionaShapelyfunction我在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文件包含從谷歌地圖的json響應API並與代碼位於相同的文件夾中。對給定行程的多段線進行解碼,然後使用Shapely將其轉換爲LineString,然後使用Fiona將每個LineString保存到shapefile中。