Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save NathanCheshire/6cb1b6dc8ca7ec8c2f49449d55fdae0c to your computer and use it in GitHub Desktop.

Select an option

Save NathanCheshire/6cb1b6dc8ca7ec8c2f49449d55fdae0c to your computer and use it in GitHub Desktop.
A python script to convert a legacy google static maps JSON style to the acceptable URL parameter format.
import json
import urllib.parse
import argparse
def color_to_hex(color):
"""Converts a color from #rrggbb to 0xrrggbb format."""
if color.startswith('#'):
return '0x' + color[1:]
return color
def encode_styler(styler):
"""Encodes a single styler dictionary to a URL component."""
parts = []
for key, value in styler.items():
if key == 'color':
value = color_to_hex(value)
parts.append(f"{key}:{value}")
return '|'.join(parts)
def encode_feature(feature):
"""Encodes a single feature dictionary to a URL component."""
feature_type = feature['featureType']
element_type = feature['elementType']
stylers = '|'.join(encode_styler(styler) for styler in feature['stylers'])
return f"feature:{feature_type}|element:{element_type}" + (f"|{stylers}" if stylers else "")
def json_to_url_encoded_schema(json_data):
"""Converts a JSON-style map data to a URL-encoded schema."""
encoded_features = [encode_feature(feature) for feature in json_data]
url_encoded_schema = '&'.join(
f"style={urllib.parse.quote(feature)}" for feature in encoded_features)
return url_encoded_schema
def main():
parser = argparse.ArgumentParser(
description='Convert a JSON file to the URL parameter encoded format for the Google Maps Static API.')
parser.add_argument('-f',
'--filepath',
required=True,
type=str,
help='Path to the JSON file containing data to be converted into URL parameter encoded format.')
args = parser.parse_args()
with open(args.filepath, 'r') as file:
json_data = json.load(file)
encoded_schema = json_to_url_encoded_schema(json_data)
print(encoded_schema)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment