user3670221
user3670221

Reputation: 31

PHP, Javascript & Twig Temaples

I have this code to show points on a google map which I just can't quite get to work when I pass the information from my PHP to my Twig template. However it works just fine with an array directly in the javascript. Please can somewhere spare my hair pulling and help me out.

PHP code:

// Create a list of items return from SQL
foreach ($mapdetails as $mapdetail){
if($locations!='') $locations.=','; 
$locations.='[
"'.$mapdetail['venue'].'"
,"'.$mapdetail['lat'].'"
,"'.$mapdetail['lng'].'"
]';    
}

// set template variables & render template
echo $template->render(array (
'pageTitle' => 'Map Locations',
'locations' => $locations
));

echoing $locations returns this: [ "Venue 1","53.301624" ,"-1.923434" ],[ "Venue 2" ,"53.160526" ,"-1.996968" ]

JAVASCRIPT SNIPPET:

When I use this line in the template it doesn't work

var all = '[{{locations|json_encode()|raw}}]';

When I use this line it does work

var all =  [[ "Venue 1" ,"53.301624" ,"-1.923434" ],[ "Venue 2","53.160526" ,"-1.996968"]];

FULL JAVASCRIPT

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>

    <script>
        // Set the Map variable
        var map;

        function initialize(){ 
            var myOptions ={
              zoom: 9,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };

THIS DOESN'T WORK When replaced with the below line it does

var all = '[{{locations|json_encode()|raw}}]';

THIS DOES WORK

var all =  [[ "Venue 1" ,"53.301624" ,"-1.923434" ],[ "Venue 2","53.160526" ,"-1.996968"]];

console.log(all);

        var infoWindow = new google.maps.InfoWindow;
        map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);

        // Set the center of the map
        var pos = new google.maps.LatLng(53.25,-1.91);
        map.setCenter(pos);

        function infoCallback(infowindow, marker) { 
            return function() {
            infowindow.open(map, marker);
        };
   }      
   function setMarkers(map, all) {  
    for (var i in all) {                    
            var venue  = all[i][0];
            var lat   = all[i][1];
            var lng   = all[i][2];
            var latlngset;

            latlngset = new google.maps.LatLng(lat, lng);

            console.log(venue);
            console.log(lat);


            var marker = new google.maps.Marker({  
              map: map,  title: city,  position: latlngset  
            });
            var content = '';       

            var infowindow = new google.maps.InfoWindow();

              infowindow.setContent(content);

              google.maps.event.addListener(
                marker, 
                'click', 
                infoCallback(infowindow, marker)
              );
          }
        }     
        // Set all markers in the all variable
        setMarkers(map, all);
      };
      // Initializes the Google Map
      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map_canvas" style="height: 500px; width: 800px;"></div>
  </body>
</html>

Any help please....

Upvotes: 1

Views: 410

Answers (1)

deceze
deceze

Reputation: 522015

The problem is that you're creating a PHP string:

'[ "Venue 1","53.301624" ,"-1.923434" ],[ "Venue 2" ,"53.160526" ,"-1.996968" ]'

which you are the json_encoding (with added quotes and stuff to boot):

var all = '[{{locations|json_encode()|raw}}]';

The result of which is something like this, which is a messed up Javascript string and not an object:

var all = '["[ \"Venue 1\",\"53.301624\"..."]';

That's nowhere close to what you want. You simply want to have a PHP array which you then json_encode:

$locations = array_map(function (array $mapdetail) {
    return array($mapdetail['venue'], $mapdetail['lat'], $mapdetail['lng']);
}, $mapdetails);

In the template:

var all = {{ locations|json_encode|raw }};

The result looks like:

var all = [["Venue 1","53.301624","-1.923434" ],["Venue 2","53.160526","-1.996968"]];

which is a Javascript array of arrays. It's that simple.

Upvotes: 2

Related Questions