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!