1

i need to use a JS Variable in in Twig.

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);".

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

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". Without the |length filter i would compare against the Collection/obejcts which of course won't work.

Further i needed to remove the "PLACEHOLDER" string because Twig will be parsed long before JS will even start running. So i need to give a legit default value, like [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.

EDIT2

I just checked if the Polyline will draw if i use dummydata, so i just tried following:

        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. If needed i can post the generated JS Code also!

5
  • 1
    var polylineCoordinates = new Array[]; isn't valid JS, it should either be var polylineCoordinates = new Array(); or preferably var polylineCoordinates = [];. I'd say check for JS errors. It might also be beneficial to add the generated JS code to your question Commented Apr 29, 2014 at 8:26
  • Thanks for that, i edited the question and the code! :) But the Polyline won't render, just the map. But that's more than i got before Commented Apr 29, 2014 at 8:52
  • Don't you just need to create your LatLng like so? polylineCoordinates.push(new google.maps.LatLng(lat, lon)); Commented Apr 29, 2014 at 10:46
  • ... and when you create lat and lon, use [i] instead of [0]: var lat = {{ turn.pois[i].lat }}; Commented Apr 29, 2014 at 10:48
  • That throws an error because he the Variable "i" is not available at the time the twig is created, because Twig is based on PHP :/ Commented Apr 29, 2014 at 11:16

1 Answer 1

0

Why do you need to use js variables in Twig? It's dirty and in your case it is useless. I suggest to fetch all coords with ajax before drawing polyine. 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.

Sign up to request clarification or add additional context in comments.

4 Comments

I wanted to use Twig because all the data i would need to draw the map are already provided by Twig because i need them for the function of the page. I wanted to decrease Requests by doing it with twig, but i guess there is no other possibility expect Ajax. Thanks! :)
@KhorneHoly there is, the simplest I know, is to create string representation of js array in twig, and use eval. i.e. <script>eval('{{twigVar}}')</script> . But ajax method is better cuz it is more flexible, and you always can cache ajax responses.
Thanks for that, i keep it in mind :) But i already built it in Ajax, i agree with you. I was just curious if it is possible with twig and JS.
In short - yes it is. But I do not know case, when it will be good solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.