简体   繁体   English

在Twig中使用JS变量

[英]Using JS Variable in Twig

i need to use a JS Variable in in Twig. 我需要在Twig中使用JS变量。

I already found this attempt and i tried it in my code below but i didn't work, the whole map won't render at all. 我已经找到了这种尝试,并在下面的代码中进行了尝试,但是我没有工作,整个地图都无法渲染。 But it will if i remove the part between "var polylineCoordinates" and "polyline.setMap(map);". 但是,如果我删除“ var polylineCoordinates”和“ polyline.setMap(map);”之间的部分,它将成功。

My task is to draw a polyline from the lat/lon Data Pois within a Turn. 我的任务是在转弯内从纬度/经度数据点画一条折线。

I posted the complete Code for the map down below. 我在下面发布了地图的完整代码。

<script type="text/javascript">
        function initialize() {
               var mapOptions = {
                   center: new google.maps.LatLng({{ turn.pois[0].lat }}, {{ turn.pois[0].lon }}),
                   zoom: 9,
                   mapTypeId: google.maps.MapTypeId.ROADMAP
               };

               var map = new google.maps.Map(document.getElementById("map_canvas"),
               mapOptions);

               var i;
               var polylineCoordinates = new Array[];
               for (i = 0; i < {{ turn.pois }}; ++i) {
                   var lat = {{ turn.pois["PLACEHOLDER"].lat }};
                   var lon = {{ turn.pois["PLACEHOLDER"].lon }};
                   polylineCoordinates.push(new google.maps.LatLng(lat.replace("PLACEHOLDER", i), lon.replace("PLACEHOLDER", i)));
                   };
               var polyline = new google.maps.Polyline({
                   path: polylineCoordinates,
                   geodesic: true,
                   strokeColor: '#FF0000',
                   strokeOpacity: 1.0,
                   strokeWeight: 2
               });
               polyline.setMap(map);
               }

         google.maps.event.addDomListener(window, 'load', initialize);
</script>

Also i'd really like some advice in general JS Coding if there's something missing or could be improved with my Code, im pretty new to JS 我也很想在一般的JS编码中找到一些建议,如果我的代码缺失或可以改进的话,这对JS来说是很新的

EDIT 编辑

I edited the Code now with the following 我现在使用以下代码编辑了代码

var polylineCoordinates = [];                
for (i = 0; i < {{ turn.pois|length }}; ++i) {
                    var lat = {{ turn.pois[0].lat }};
                    var lon = {{ turn.pois[0].lon }};
                    polylineCoordinates.push(new google.maps.LatLng(lat.replace(0, i), lon.replace(0, i)));
                };

Just for explaination for People that'll see this Question in a future time: I needed to add the |length at {{ turn.pois|length }} so it will compare with an intiger that stands for all elements in the collection "pois". 只是为了对以后会遇到此问题的人们进行解释:我需要在{{ turn.pois|length }}处添加| length,以便将其与代表“ pois”集合中所有元素的Intiger进行比较。 ”。 Without the |length filter i would compare against the Collection/obejcts which of course won't work. 如果没有| length过滤器,我将与Collection / obejcts进行比较,这当然是行不通的。

Further i needed to remove the "PLACEHOLDER" string because Twig will be parsed long before JS will even start running. 另外,我需要删除“ PLACEHOLDER”字符串,因为Twig将在JS甚至开始运行之前就被解析。 So i need to give a legit default value, like [0]. 因此,我需要提供一个合法的默认值,例如[0]。 (the first element in the collection) (集合中的第一个元素)

The map is rendering now, but without the Polyline. 地图现在正在渲染,但没有折线。 I'm guessing that the replace() isn't working. 我猜测replace()无法正常工作。

EDIT2 EDIT2

I just checked if the Polyline will draw if i use dummydata, so i just tried following: 我只是检查了如果我使用dummydata是否会绘制折线,所以我尝试了以下操作:

        var polylineCoordinates = [
            new google.maps.LatLng(54.180260, 12.098421),
            new google.maps.LatLng(54.180348, 12.198463),
            new google.maps.LatLng(54.256842, 12.324694),
            new google.maps.LatLng(54.328642, 12.468212)
        ];
        /*for (i = 0; i < {{ turn.pois|length }}; ++i) {
            var lat = {{ turn.pois[0].lat }};
            var lon = {{ turn.pois[0].lon }};
            polylineCoordinates.push(new google.maps.LatLng(lat.replace(0, i), lon.replace(0, i)));
        };*/

It perfectly worked! 完美地工作了! So my problem is the way to replace the [0] with the i Variable from JavaScript. 所以我的问题是用JavaScript中的i变量替换[0]的方法。 If needed i can post the generated JS Code also! 如果需要,我还可以发布生成的JS代码!

Why do you need to use js variables in Twig? 为什么需要在Twig中使用js变量? It's dirty and in your case it is useless. 它很脏,在您的情况下是没有用的。 I suggest to fetch all coords with ajax before drawing polyine. 我建议在绘制polyine之前使用ajax获取所有坐标。 It will be like: 它将像:

 jQuery.ajax({
     url:    'http://example.com/getCoords',
     dataType: 'json'

     success: function(result) {
         //your array with coords;
         var polylineCoordinates = [];
                      console.log(result); //just to see what we have
                      $.each(result, function(i, item) {
                          polyineCoordinates = new google.maps.LatLng(item.lat, item.lng);
                      });
              },
     async:   false
});         

and after this, - you can draw. 然后,-您可以绘制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM