Please take a look at the below Python code and ask any questions or make suggestions to improve the code. This is not our real code, but we will want to make a function that appears like:
In this case bbox is the geographic bounding area, type is the API endpoint (points, traffic signs, images, sequences), and filter would likely want to use a format with an operator (>=, ==, <, contains, etc) for the properties of the returned data, for example a map feature in the example code matching the value for a street light, but we could filter also by date > than a given input.
We also want to consider a function that would save the data to file, maybe like saveGeoJSON(path)
.
import mercantile, mapbox_vector_tile, requests, json
from vt2geojson.tools import vt_bytes_to_geojson
# define an empty geojson as output
output= { "type": "FeatureCollection", "features": [] }
# vector tile endpoints -- change this in the API request to reference the correct endpoint
tile_points = 'mly_map_feature_point'
tile_traffic_signs = 'mly_map_feature_traffic_sign'
# Mapillary access token -- user should provide their own
access_token = 'MLY|XXX'
# a bounding box in [east_lng,_south_lat,west_lng,north_lat] format
east, south, west, north = [-80.13423442840576,25.77376933762778,-80.1264238357544,25.788608487732198]
# list of values to filter for and keep -- update this if changing to traffic signs
filter_values = ['object--support--utility-pole','object--street-light']
# get the tiles with x and y coordinates which intersect our bounding box, MUST be at zoom level 14 where the data is available
tiles = list(mercantile.tiles(east, south, west, north, 14))
# loop through all tiles to get IDs of Mapillary data
for tile in tiles:
tile_url = 'https://tiles.mapillary.com/maps/vtp/{}/2/{}/{}/{}?access_token={}'.format(tile_points,tile.z,tile.x,tile.y,access_token)
response = requests.get(tile_url)
data = vt_bytes_to_geojson(response.content, tile.x, tile.y, tile.z)
# filter for only features matching the values in filter list above
filtered_data = [feature for feature in data['features'] if feature['properties']['value'] in filter_values]
# check if features are inside bbox, and push to output geojson object if yes
for feature in filtered_data:
if (feature['geometry']['coordinates'][0] > east and feature['geometry']['coordinates'][0] < west)\
and (feature['geometry']['coordinates'][1] > south and feature['geometry']['coordinates'][1] < north):
output['features'].append(feature)
# save a local geojson with the filtered data
with open('mydata.geojson', 'w') as f:
json.dump(output, f)