-1
GoogleのDirections APIから返されたjsonを取得し、その情報をルートのポリラインと同じシェープファイルの線に変換できますか?Googleの方向をシェープファイルの行に変換する
私はQGISで作っている地図で行った旅行をプロットしたいと思います。
GoogleのDirections APIから返されたjsonを取得し、その情報をルートのポリラインと同じシェープファイルの線に変換できますか?Googleの方向をシェープファイルの行に変換する
私はQGISで作っている地図で行った旅行をプロットしたいと思います。
私は最終的にFionaとShapelyを使用してこれを行う方法を考え出したと私は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マップからjson
応答が含まれていることを前提としていAPIであり、コードと同じフォルダにあります。与えられたトリップのポリラインはデコードされ、Shapelyを使用してLineString
に変換され、各LineString
はFionaを使用してシェープファイルに保存されます。