I would like to plot a list of markers on a google map. I generate some Javascript code using Python. I read this : google map api: open url by clicking at marker and try to adapt my code but it still doesn t work : all I am able to plot is the first maker and the url doesn' t even look like it is working.
Here is what I produced since then - I tried to keep it as simple as possible.
from __future__ import print_function
class Mappy(object):
def __init__(self,listCord=[]):
self.listCord = listCord
def __str__(self):
initLat = sum(( x[0] for x in self.listCord)) / len(self.listCord)
initLon = sum(( x[1] for x in self.listCord)) / len(self.listCord)
markersCode = "\n".join(
[ """new google.maps.Marker({
position: new google.maps.LatLng(%s,%s),
map: map,
title : '%s',
url : '%s'
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
"""%(x[0], x[1],x[2],x[2])
for x in self.listCord])
print (markersCode)
return """
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<div id="map-canvas" style="height: 100%; width: 100%"></div>
<script type="text/javascript">
var map;
function show_map() {{
map = new google.maps.Map(document.getElementById("map-canvas"), {{
zoom: 8,
center: new google.maps.LatLng({centerLat}, {centerLon})
}});
{markersCode}
}}
google.maps.event.addDomListener(window, 'load', show_map);
</script>
""".format(centerLat=initLat, centerLon=initLon,
markersCode=markersCode)
Now that the class tht will generate the list of marker is set up, this is my main:
if __name__ == "__main__":
listCord = [[51.5248,-0.133427,'Old Trafford','http://www.manutd.com'],
[51.5145,-0.157687,'Stamford Bridge','http://www.chelseafc.com'],
[51.5264,-0.13892,'Anfield','http://www.liverpoolfc.com']]
mapper = Mappy(listCord)
with open('stadium.html','w') as out :
print(mapper,file=out)
This will return a HTML file where I am suposed to see my place of interest with their link. But it doesnt work. I have to say that if I don t put the :
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
I can then see all the place on my map with their title.
Thanks in advance for your help