Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

I built a custom google map php file to implement into the front page of my drupal site that uses both javascript and php, and it is being called via drupal_add_js in the template.php file. I'm having a hard time figuring out how to properly run the PHP within the javascript, and then set the results to the JavaScript variable markers. I'm attempting to push each result to an array and echo the array via json_encode($item); however, in my console, i'm getting an error that is Cannot read property 'lat' of undefined.

Here is my entire map.php:

var map = null;
var infowindow = new google.maps.InfoWindow();
var markers = [Drupal.settings.markers];

window.onload = function () {

var mapOptions = {
    center: new google.maps.LatLng(
        parseFloat(markers[0].lat),
        parseFloat(markers[0].lng)),
    zoom: 13,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};
var path = new google.maps.MVCArray();
var service = new google.maps.DirectionsService();
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var poly = new google.maps.Polyline({map: map, strokeColor: '#F3443C'});

var lat_lng = new Array();
           for (i = 0; i < markers.length; i++) {
           var data = markers[i]
           var myLatlng = new google.maps.LatLng(data.lat, data.lng);
           lat_lng.push(myLatlng);
           var marker = new google.maps.Marker({
               position: myLatlng,
               map: map,
               title: data.title
           });
           (function (marker, data) {
               google.maps.event.addListener(marker, "click", function (e) {
                   infoWindow.setContent(data.description);
                   infoWindow.open(map, marker);
               });
           })(marker, data);
       }
for (var i = 0; i < markers.length; i++) {
    if ((i + 1) < markers.length) {
        var src = new google.maps.LatLng(parseFloat(markers[i].lat), 
                                         parseFloat(markers[i].lng));
        var des = new google.maps.LatLng(parseFloat(markers[i+1].lat), 
                                         parseFloat(markers[i+1].lng));
        service.route({
            origin: src,
            destination: des,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        }, function (result, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                    path.push(result.routes[0].overview_path[i]);
                }
                poly.setPath(path);
            }
        });
    }
}
} 

and here is my page--front.tpl.php with my attempt in creating the array that will be accessible to my js file:

<?php

  if (isset($_GET['routeselected'])) 
  {
  $result = mysqli_query($db, "SELECT * FROM STOP INNER JOIN RouteStop ON Stop.Stop_ID = RouteStop.Stop_ID WHERE RouteStop.Route_ID = " . (int)$_GET['routeselected'] . " AND RouteStop.Company_ID = " . (int)$_GET['companyselected']);
  $markers = array();
  while (($row = mysqli_fetch_array($result))){
      $markers[$row['title']] = array($row['Stop_ID']);
      $markers[$row['lat']] = array($row['Latitude']);
      $markers[$row['lng']] = array($row['Longitude']);
      $markers[$row['description']] = array($row['StopName']);
      }
    drupal_json_encode($markers);
    drupal_add_js(array('markers' => drupal_json_encode($markers)), 'setting');
  }
  ?>

Does anyone possibly know the solution to my issue? Thank you for all and any help!

share|improve this question

marked as duplicate by jeroen, George Cummins, tereško, mustaccio, Frank van Puffelen May 5 at 17:16

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
thanks, so basically just add json_encode() like so? <?php echo " {\"title\": '".json_encode($row['Stop_ID']).";} ?> –  webhoodlum May 5 at 15:59
    
No, you don't output anything until the end of your script / database operation. You add everything to an array and at the end json_encode that array. –  jeroen May 5 at 16:00

1 Answer 1

Writing inline PHP code inside javascript file is really a bad idea.

The solution is:

  • Move that php code to a module
  • Generate $markers as a PHP associative array/object
  • Convert it to JSON using drupal_json_encode($markers)
  • Add it to Drupal.settings.markers using drupal_add_js(array('markers' => drupal_json_encode($markers)), 'setting');
  • And in your js use var markers = Drupal.settings.markers

For more details, have a look at this article: https://drupal.org/node/756722#settings-javascript

share|improve this answer
    
Thank you for your response! Will it work if I just generate $markers in my page--front.tpl.php? I've attempted to rework my code, i will alter my question with the rework. It still does not work, I think I may be populating the array incorrectly. Do you mind taking a look at my new code? –  webhoodlum May 5 at 20:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.