在谷歌地图标记上添加网址?

时间:2015-06-25 16:53:01

标签: javascript python-2.7 url google-maps-markers

我想在谷歌地图上绘制标记列表。我使用Python生成一些Javascript代码。我读了这个:google map api: open url by clicking at marker并尝试调整我的代码,但它仍然无法工作:我能够绘制的所有内容都是第一个制作者,而网址看起来甚至看起来都不起作用。

以下是我自那时起制作的内容 - 我尽量保持简单。

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)

现在该类将生成标记列表已设置,这是我的主要内容:

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)

这将返回一个HTML文件,我可以通过链接查看我感兴趣的地方。但它不起作用。我不得不说,如果我不把:

google.maps.event.addListener(marker, 'click',   function() {
        window.location.href = this.url;
        });
然后,我可以看到我的地图上所有地方的标题。

提前感谢您的帮助

1 个答案:

答案 0 :(得分:0)

看起来您只需要更改代码的一行就能使其正常工作!

尝试使用window.open(marker.url);代替window.location.href = marker.url;

查看示例here