Skip to content

Commit 6fcdf85

Browse files
committed
WIP: Update dependencies and functionality
- Update dependencies (Flask, mypy, python >3.8) - Load javascript in an async manner - Replace obsolete `Marker` with `AdvancedMarkerElement`
1 parent 093f143 commit 6fcdf85

File tree

5 files changed

+571
-293
lines changed

5 files changed

+571
-293
lines changed

examples/templates/example.html

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,8 @@ <h2>You can move markers dynamically and add new markers, refresh its position e
151151
<br />
152152
<button onclick='movingmap_markers.map(function(mk){mk.setMap(null)})'>Remove marker</button>
153153
<button onclick='movingmap_markers.map(function(mk){mk.setMap(movingmap)})'>Restore marker</button>
154-
<button onclick='new google.maps.Marker({title: "New Marker", position: {lat: 37.4640, lng: -122.1350}}).setMap(movingmap)'>Add New Marker Above</button>
154+
const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
155+
<button onclick='new AdvancedMarkerElement({title: "New Marker", position: {lat: 37.4640, lng: -122.1350}}).setMap(movingmap)'>Add New Marker Above</button>
155156

156157

157158
<pre>
@@ -161,7 +162,7 @@ <h2>You can move markers dynamically and add new markers, refresh its position e
161162
&lt;button onclick='movingmap_markers.map(function(mk){mk.setPosition({lat: 37.449, lng:-122.135})})'&gt;Go to position 4 &lt;/button&gt;
162163
&lt;button onclick='movingmap_markers.map(function(mk){mk.setMap(null)})'&gt;Remove marker&lt;/button&gt;
163164
&lt;button onclick='movingmap_markers.map(function(mk){mk.setMap(movingmap)})'&gt;Restore marker&lt;/button&gt;
164-
&lt;button onclick='onclick='new google.maps.Marker({title: "New Marker", position: {lat: 37.4640, lng: -122.1350}}).setMap(movingmap)''&gt;Add new marker above&lt;/button&gt;
165+
&lt;button onclick='onclick='AdvancedMarkerElement({title: "New Marker", position: {lat: 37.4640, lng: -122.1350}}).setMap(movingmap)''&gt;Add new marker above&lt;/button&gt;
165166
</pre>
166167

167168

flask_googlemaps/__init__.py

Lines changed: 24 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
"""FlaskGoogleMaps - Google Maps Extension for Flask"""
22

3-
__version__ = "0.4.1"
3+
__version__ = "0.4.2"
44

55
from json import dumps
6-
from typing import Optional, Dict, Any, List, Union, Tuple, Text # noqa: F401
7-
6+
from typing import Optional, Dict, Any, List, Union, Tuple, Text
87
import requests
9-
from flask import Blueprint, Markup, g, render_template
8+
from flask import Blueprint, g, render_template
9+
from markupsafe import Markup
1010

11-
from flask_googlemaps.icons import dots, Icon # noqa: F401
11+
from flask_googlemaps.icons import dots, Icon
1212

1313
DEFAULT_ICON = dots.red
1414
DEFAULT_CLUSTER_IMAGE_PATH = "static/images/m"
@@ -28,8 +28,7 @@ def __init__(
2828
cls="map", # type: str
2929
language="en", # type: str
3030
region="US", # type: str
31-
rectangles=None,
32-
# type: Optional[List[Union[List, Tuple, Tuple[Tuple], Dict]]]
31+
rectangles=None, # type: Optional[List[Union[List, Tuple, Tuple[Tuple], Dict]]]
3332
circles=None, # type: Optional[List[Union[List, Tuple, Dict]]]
3433
polylines=None, # type: Optional[List[Union[List, Tuple, Dict]]]
3534
polygons=None, # type: Optional[List[Union[List, Tuple, Dict]]]
@@ -258,20 +257,13 @@ def build_rectangle_dict(
258257
"stroke_weight": stroke_weight,
259258
"fill_color": fill_color,
260259
"fill_opacity": fill_opacity,
261-
"bounds": {
262-
"north": north,
263-
"west": west,
264-
"south": south,
265-
"east": east,
266-
},
260+
"bounds": {"north": north, "west": west, "south": south, "east": east},
267261
}
268262

269263
return rectangle
270264

271-
def add_rectangle(
272-
self, north=None, west=None, south=None, east=None, **kwargs
273-
):
274-
# type: (Optional[float], Optional[float], Optional[float], Optional[float], **Any) -> None # noqa: E501
265+
def add_rectangle(self, north=None, west=None, south=None, east=None, **kwargs):
266+
# type: (Optional[float], Optional[float], Optional[float], Optional[float], **Any) -> None
275267
"""Adds a rectangle dict to the Map.rectangles attribute
276268
277269
The Google Maps API describes a rectangle using the LatLngBounds
@@ -306,9 +298,7 @@ def add_rectangle(
306298
if east:
307299
kwargs["bounds"]["east"] = east
308300

309-
if set(("north", "east", "south", "west")) != set(
310-
kwargs["bounds"].keys()
311-
):
301+
if set(("north", "east", "south", "west")) != set(kwargs["bounds"].keys()):
312302
raise AttributeError("rectangle bounds required to rectangles")
313303

314304
kwargs.setdefault("stroke_color", "#FF0000")
@@ -357,9 +347,7 @@ def build_circles(self, circles):
357347
elif isinstance(circle, (tuple, list)):
358348
if len(circle) != 3:
359349
raise AttributeError("circle requires center and radius")
360-
circle_dict = self.build_circle_dict(
361-
circle[0], circle[1], circle[2]
362-
)
350+
circle_dict = self.build_circle_dict(circle[0], circle[1], circle[2])
363351
self.add_circle(**circle_dict)
364352

365353
def build_circle_dict(
@@ -408,9 +396,7 @@ def build_circle_dict(
408396

409397
return circle
410398

411-
def add_circle(
412-
self, center_lat=None, center_lng=None, radius=None, **kwargs
413-
):
399+
def add_circle(self, center_lat=None, center_lng=None, radius=None, **kwargs):
414400
# type: (Optional[float], Optional[float], Optional[float], **Any) -> None
415401
"""Adds a circle dict to the Map.circles attribute
416402
@@ -759,16 +745,14 @@ def build_heatmap(self, heatmap_data, heatmap_layer):
759745
raise AttributeError("heatmap_later requires 'heatmap_data'")
760746
if not isinstance(heatmap_data, (list)):
761747
raise AttributeError(
762-
"heatmap_data only accepts a list of dicts with keys "
763-
"'lat' 'lng' and their corresponding values"
748+
"heatmap_data only accepts a list of dicts with keys 'lat' 'lng' and their corresponding values"
764749
)
765750
for hm in heatmap_data:
766751
if isinstance(hm, dict):
767752
self.add_heatmap(**hm)
768753
else:
769754
raise AttributeError(
770-
"elements of list 'heatmap_data' must be a dict of keys "
771-
"'lat' and 'lng' with their corresponding values"
755+
"elements of list 'heatmap_data' must be a dict of keys 'lat' and 'lng' with their corresponding values"
772756
)
773757

774758
def add_heatmap(self, lat=None, lng=None, **kwargs):
@@ -780,9 +764,7 @@ def add_heatmap(self, lat=None, lng=None, **kwargs):
780764
if "lat" not in kwargs or "lng" not in kwargs:
781765
raise AttributeError("heatmap_data requires 'lat' and 'lng' values")
782766
if len(kwargs) > 2:
783-
raise AttributeError(
784-
"heatmap_data can only contain 'lat' and 'lng' values"
785-
)
767+
raise AttributeError("heatmap_data can only contain 'lat' and 'lng' values")
786768

787769
self.heatmap_data.append(kwargs)
788770

@@ -839,9 +821,7 @@ def verify_lat_lng_coordinates(self, lat, lng):
839821
def js(self):
840822
# type: () -> Markup
841823
return Markup(
842-
self.render(
843-
"googlemaps/gmapjs.html", gmap=self, DEFAULT_ICON=DEFAULT_ICON
844-
)
824+
self.render("googlemaps/gmapjs.html", gmap=self, DEFAULT_ICON=DEFAULT_ICON)
845825
)
846826

847827
@property
@@ -881,30 +861,18 @@ def set_googlemaps_loaded():
881861
def get_address(API_KEY, lat, lon):
882862
# type: (str, float, float) -> dict
883863
add_dict = dict()
884-
response = requests.get(
864+
response = rq.get(
885865
"https://maps.googleapis.com/maps/api/geocode/json?latlng="
886866
+ ",".join(map(str, [lat, lon]))
887867
+ "&key="
888868
+ API_KEY
889869
).json()
890-
add_dict["zip"] = response["results"][0]["address_components"][-1][
891-
"long_name"
892-
]
893-
add_dict["country"] = response["results"][0]["address_components"][-2][
894-
"long_name"
895-
]
896-
add_dict["state"] = response["results"][0]["address_components"][-3][
897-
"long_name"
898-
]
899-
add_dict["city"] = response["results"][0]["address_components"][-4][
900-
"long_name"
901-
]
902-
add_dict["locality"] = response["results"][0]["address_components"][-5][
903-
"long_name"
904-
]
905-
add_dict["road"] = response["results"][0]["address_components"][-6][
906-
"long_name"
907-
]
870+
add_dict["zip"] = response["results"][0]["address_components"][-1]["long_name"]
871+
add_dict["country"] = response["results"][0]["address_components"][-2]["long_name"]
872+
add_dict["state"] = response["results"][0]["address_components"][-3]["long_name"]
873+
add_dict["city"] = response["results"][0]["address_components"][-4]["long_name"]
874+
add_dict["locality"] = response["results"][0]["address_components"][-5]["long_name"]
875+
add_dict["road"] = response["results"][0]["address_components"][-6]["long_name"]
908876
add_dict["formatted_address"] = response["results"][0]["formatted_address"]
909877
return add_dict
910878

@@ -942,9 +910,7 @@ def init_app(self, app):
942910
app.add_template_global(googlemap_obj)
943911
app.add_template_filter(googlemap)
944912
app.add_template_global(googlemap)
945-
app.add_template_global(
946-
app.config.get("GOOGLEMAPS_KEY"), name="GOOGLEMAPS_KEY"
947-
)
913+
app.add_template_global(app.config.get("GOOGLEMAPS_KEY"), name="GOOGLEMAPS_KEY")
948914
app.add_template_global(set_googlemaps_loaded)
949915
app.add_template_global(is_googlemaps_loaded)
950916

flask_googlemaps/templates/googlemaps/gmapjs.html

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
{% if not is_googlemaps_loaded() and not gmap.heatmap_layer %} {% if GOOGLEMAPS_KEY %}
2-
<script src="//maps.googleapis.com/maps/api/js?key={{GOOGLEMAPS_KEY}}&map_ids={{gmap.map_ids}}&language={{gmap.language}}&region={{gmap.region}}" type="text/javascript"></script>
2+
<script async src="//maps.googleapis.com/maps/api/js?key={{GOOGLEMAPS_KEY}}&map_ids={{gmap.map_ids}}&language={{gmap.language}}&region={{gmap.region}}" type="text/javascript"></script>
33
{% else %}
4-
<script src="//maps.googleapis.com/maps/api/js?language={{gmap.language}}&region={{gmap.region}}" type="text/javascript"></script>
4+
<script async src="//maps.googleapis.com/maps/api/js?language={{gmap.language}}&region={{gmap.region}}" type="text/javascript"></script>
55
{% endif %} {{ set_googlemaps_loaded() }} {% endif %}{% if gmap.cluster %}
66
<script src="//cdnjs.cloudflare.com/ajax/libs/js-marker-clusterer/1.0.0/markerclusterer_compiled.js" type="text/javascript"></script>
77
{% endif %}{% if gmap.heatmap_layer %}{% if GOOGLEMAPS_KEY %}
8-
<script src="//maps.googleapis.com/maps/api/js?key={{GOOGLEMAPS_KEY}}&map_ids={{gmap.map_ids}}&language={{gmap.language}}&region={{gmap.region}}&libraries=visualization" type="text/javascript"></script>
8+
<script async src="//maps.googleapis.com/maps/api/js?key={{GOOGLEMAPS_KEY}}&map_ids={{gmap.map_ids}}&language={{gmap.language}}&region={{gmap.region}}&libraries=visualization" type="text/javascript"></script>
99
{% endif %}{% endif%}
1010

1111

@@ -23,7 +23,7 @@
2323
var {{gmap.varname}}_polylines = [];
2424
var prev_infowindow_{{gmap.varname}} = null;
2525

26-
function initialize_{{gmap.varname}}() {
26+
async function initialize_{{gmap.varname}}() {
2727
document.getElementById('{{gmap.identifier}}').style.display = 'block';
2828
{{gmap.varname}} = new google.maps.Map(
2929
document.getElementById('{{gmap.identifier}}'), {
@@ -37,7 +37,8 @@
3737
rotateControl: {% if gmap.rotate_control %}true{% else %}false{% endif %},
3838
scrollwheel: {% if gmap.scroll_wheel %}true{% else %}false{% endif %},
3939
fullscreenControl: {% if gmap.fullscreen_control %}true{% else %}false{% endif %},
40-
styles: {{ gmap.styles | tojson }}
40+
styles: {{ gmap.styles | tojson }},
41+
mapId: "{{ gmap.mapId if gmap.mapId is defined else 'DEMO_MAP_ID' }}"
4142
});
4243

4344
//center map location on user location
@@ -82,13 +83,12 @@
8283

8384
// add gmap markers
8485
var raw_markers = {{gmap.markers|tojson|safe}};
86+
const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
8587
for(i=0; i<{{gmap.markers|length}};i++) {
86-
tempMarker = new google.maps.Marker({
88+
tempMarker = new AdvancedMarkerElement({
8789
position: new google.maps.LatLng(raw_markers[i].lat, raw_markers[i].lng),
8890
map: {{gmap.varname}},
89-
icon: raw_markers[i].icon,
9091
title: raw_markers[i].title ? raw_markers[i].title : null,
91-
label: raw_markers[i].label ? raw_markers[i].label : null
9292
});
9393

9494

@@ -298,6 +298,6 @@
298298
window.onload = init_{{gmap.identifier}}_button;
299299
}
300300
{% else %}
301-
google.maps.event.addDomListener(window, 'load', initialize_{{gmap.varname}});
301+
window.addEventListener('load', initialize_{{gmap.varname}});
302302
{% endif %}
303303
</script>

0 commit comments

Comments
 (0)