在Javascript中添加Google地图标记与DJango模板标记 [英] Adding Google Map Markers with DJango Template Tags in Javascript

查看:244
本文介绍了在Javascript中添加Google地图标记与DJango模板标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Django模板标签变量作为纬度和经度添加一堆地图标记到地图上,但是事情并不奏效。这是我在视图中的JavaScript代码。我将代码作为外部JS文件加载。这是我必须初始化一切。此外,当我这样做谷歌地图甚至没有出现了。它消失了。

I am trying to add a bunch of map markers to a map using Django template tag variables as the latitude and longitude but things aren't working too well. Here is what I have in the view javascript code. I load the code in as an external JS file. Here is what i have to initialize everything. Also when I did this the google map didn't even show up any more. It disappeared.

 function initialize() {
            var latLng = new google.maps.LatLng(41.85, -87.65);

            map = new google.maps.Map(document.getElementById('map_canvas'), {
                zoom: 8,
                center: latLng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });



             marker = new google.maps.Marker({
                position: latLng,
                title: 'Point A',
                map: map,
                draggable: true
            });

            // Update current position inf o and load in markers from database
            loadMarkers();
            updateMarkerPosition(latLng);
            geocodePosition(latLng);

这里是loadMarkers()看起来像

And here is what loadMarkers() looks like

            function loadMarkers(){
            {% for mark in latest_marks %}
            var point = new google.maps.LatLng({{mark.lat}},{{mark.lng}});
                var marker = new google.maps.Marker({
                position: point,
                map: map,
            });
            {% endfor %}    
        }

任何帮助将不胜感激。干杯。

Any help would be appreciated. Cheers.

推荐答案

您不能将Django模板标签放在外部的javascript文件中。 Django甚至没有看到那些。您的网络服务器直接向客户端提供服务。

You can't put Django template tags inside external javascript files. Django doesn't even see those. Your webserver serves those directly to the client.

您可以做的是使用Django生成Javascript变量和数据结构,例如在您的模板中的< script> 标签内,然后您的外部javascript文件可以引用那些。

What you can do is use Django to generate Javascript variables and data structures, e.g. inside <script> tags in your template, and then your external javascript files can reference those just fine.

例如在您的模板中,您可以使Django生成:

E.g. in your template, you can have Django generate:

<script>var myVar = {something: 42};</script>

然后您的外部JavaScript文件可以使用 myVar 。我做了很多这样做来定制外部JavaScript脚本的行为。

And your external javascript file can then make use of myVar. I do this a lot to customize the behavior of external javascript scripts.

而且,正如我在评论中提到的,你有一个逗号:地图:地图,。这将产生错误并停止脚本。

And, as I mentioned in the comment, you have a trailing comma: map: map,. This will produce an error and halt your script.

这篇关于在Javascript中添加Google地图标记与DJango模板标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆