0

I am wondering how I might add variables from my php code into a javascript code.

For example, my query results in vertreklat, vertreklong, aankomstlat, aankomstlong

My javascript code:

echo "<script src='http://maps.googleapis.com/maps/api/js?sensor=false'></script>
<script>
/* ***** Start CustomMarker ***** */
function CustomMarker(latlng, map, marker_id, hovercard) {
  this.latlng_ = latlng;
  this.marker_id = marker_id;
  this.hovercard_content = hovercard;
  this.setMap(map);
}

CustomMarker.prototype = new google.maps.OverlayView();

CustomMarker.prototype.draw = function() {
  var me = this;
  var div = this.div_;
  if (!div) {
    div = this.div_ = document.createElement('DIV'); 
        div.id=me.marker_id;
    var panes = this.getPanes();
    panes.overlayImage.appendChild(div);
  }
  var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);
  if (point) {
      div.className = 'map-marker show-hovercard';
      div.style.left = (point.x-6) + 'px';
      div.style.top = (point.y-23) + 'px';
      $(div).attr('data-hovercard-content', me.hovercard_content);

  }
};

CustomMarker.prototype.remove = function() {
  if (this.div_) {
    this.div_.parentNode.removeChild(this.div_);
    this.div_ = null;
  }
};

CustomMarker.prototype.getPosition = function() {
 return this.latlng_;
};
/* ***** End CustomMarker ***** */

function initialize() {
  var markers = [];
  var bounds = new google.maps.LatLngBounds();
  var myOptions = {
    center: new google.maps.LatLng(20, 20), 
    zoom: 2,
    mapTypeId: google.maps.MapTypeId.TERRAIN,
    panControl: false,
    streetViewControl: false,
    zoomControlOptions: {
        style: google.maps.ZoomControlStyle.SMALL
    }
  };
  var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
        pos = new google.maps.LatLng(vertreklat, vertreklong);
    overlay = new CustomMarker(pos, map, 'marker_KMSP', 'some name');
    overlay.setMap(map);
        bounds.extend(pos);
            pos = new google.maps.LatLng(aankomstlat, aankomstlong);
    overlay = new CustomMarker(pos, map, 'marker_RJAA', 'some name');
    overlay.setMap(map);
        bounds.extend(pos);

      var flightPath = new google.maps.Polyline({path: [new   
google.maps.LatLng(vertreklat, vertreklong),new google.maps.LatLng(aankomstlat,   
aankomstlong)], strokeColor: '#ffffff', strokeOpacity: 0.7, strokeWeight: 2, geodesic: 
true });
      flightPath.setMap(map);



  map.fitBounds(bounds);google.maps.event.addListener(map, 'zoom_changed', 
function() {
      if(map.getZoom()<2) {
        map.setZoom(2); 
        }
    });
}
$(document).ready(function() {
    initialize();
});
</script>";

All of the data that needs to come from my query goes within this part of the script:

var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
        pos = new google.maps.LatLng(**vertreklat, vertreklong**);
    overlay = new CustomMarker(pos, map, 'marker_KMSP', 'some name');
    overlay.setMap(map);
        bounds.extend(pos);
            pos = new google.maps.LatLng(**aankomstlat, aankomstlong**);
    overlay = new CustomMarker(pos, map, 'marker_RJAA', 'some name');
    overlay.setMap(map);
        bounds.extend(pos);

      var flightPath = new google.maps.Polyline({path: [new   
google.maps.LatLng(**vertreklat, vertreklong**),new google.maps.LatLng(**aankomstlat,   
aankomstlong**)], strokeColor: '#ffffff', strokeOpacity: 0.7, strokeWeight: 2, geodesic: 
true });
      flightPath.setMap(map);

But I am confused as to how to accomplish this task....

  • If you have the values in your server-side code when you perform that one large `echo` statement, you can just include the PHP values in the string being `echo`ed: http://stackoverflow.com/questions/5605965/php-concatenate-or-directly-insert-variables-in-string – David Sep 08 '13 at 22:10
  • So you're trying to assign PHP variables from JavaScript then use them in later JavaScript? Won't work (been asked a million times. Look up client/server-side code for info). Just keep it all in JavaScript; don't get the PHP involved at all. Unless your second code block is PHP (if it is, it's heavily broken!) in which case, yeah, just echo the values. – Dave Sep 08 '13 at 22:14

3 Answers3

0

Try this:

var flightPath = new google.maps.Polyline({path: [new   
google.maps.LatLng(".$row['vertreklat'].",".$row['vertreklong']."),new google.maps.LatLng(".$row['aankomstlat'].",".$row['aankomstlong'].")], strokeColor: '#ffffff', strokeOpacity: 0.7, strokeWeight: 2, geodesic: 
true });

Since you started the echo wqith double quotes you can use them again to break the string and concatenate with dot .. By the way should your PHP variables not have a $ ?

Sergio
  • 28,539
  • 11
  • 85
  • 132
  • this does not seem to work. when I look at the html code after reloading the page I get: var flightPath = new google.maps.Polyline({path: [new google.maps.LatLng(vertreklat,vertreklong),new google.maps.LatLng(aankomstlat,aankomstlong)], strokeColor: '#ffffff', strokeOpacity: 0.7, strokeWeight: 2, geodesic: true }); the ** were meant to symbolize the bold, but i realized you can't bold code. I also tried with using $, that broke the code. –  Sep 08 '13 at 22:31
  • i also tried doing .$row['vertreklat'].",".$row['vertreklong']. and {$aankomstlat},{$aankomstlong} but both of those yielded (,) in the html.. –  Sep 08 '13 at 22:40
  • i verified that there is in fact data that should show up when I run my query... there is... –  Sep 08 '13 at 22:42
  • @DaniëlCronk, if you echo just `$row['vertreklong']` what do you get? – Sergio Sep 08 '13 at 22:43
  • Sergio - it's very odd, i really don't get anything. but when i put my code into Toad and run it the value is there... –  Sep 08 '13 at 23:20
  • the issue, my stupidity, my javascript was not included in the while... once i moved it up, it populated correctly. well, mostly. there's still one issue with the line, but otherwise, –  Sep 09 '13 at 00:04
  • @DaniëlCronk, yes you should use $row['vertreklong'] inside the while. What "issue" is still missing? – Sergio Sep 09 '13 at 06:45
  • nothing is missing. i figured it out once I put the code up in the {while} loop. The only thing I have to figure out now, is how to handle cases where there are ' in names that will come in the .$row['aankomstnaam']. which i have altered my code to include. –  Sep 09 '13 at 10:32
0

For such long blocks of output, instead of echo return back literal output with ?>. Then insert small blocks of <?php ... ?> where you need to echo variables.

?>
<script src='http://maps.googleapis.com/maps/api/js?sensor=false'></script>
<script>
/* ***** Start CustomMarker ***** */
function CustomMarker(latlng, map, marker_id, hovercard) {
  this.latlng_ = latlng;
  this.marker_id = marker_id;
  this.hovercard_content = hovercard;
  this.setMap(map);
}

CustomMarker.prototype = new google.maps.OverlayView();

CustomMarker.prototype.draw = function() {
  var me = this;
  var div = this.div_;
  if (!div) {
    div = this.div_ = document.createElement('DIV'); 
        div.id=me.marker_id;
    var panes = this.getPanes();
    panes.overlayImage.appendChild(div);
  }
  var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);
  if (point) {
      div.className = 'map-marker show-hovercard';
      div.style.left = (point.x-6) + 'px';
      div.style.top = (point.y-23) + 'px';
      $(div).attr('data-hovercard-content', me.hovercard_content);

  }
};

CustomMarker.prototype.remove = function() {
  if (this.div_) {
    this.div_.parentNode.removeChild(this.div_);
    this.div_ = null;
  }
};

CustomMarker.prototype.getPosition = function() {
 return this.latlng_;
};
/* ***** End CustomMarker ***** */

function initialize() {
  var markers = [];
  var bounds = new google.maps.LatLngBounds();
  var myOptions = {
    center: new google.maps.LatLng(20, 20), 
    zoom: 2,
    mapTypeId: google.maps.MapTypeId.TERRAIN,
    panControl: false,
    streetViewControl: false,
    zoomControlOptions: {
        style: google.maps.ZoomControlStyle.SMALL
    }
  };
  var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
        pos = new google.maps.LatLng(<?php echo $vertreklat ?>, <?php echo $vertreklong ?>);
    overlay = new CustomMarker(pos, map, 'marker_KMSP', 'some name');
    overlay.setMap(map);
        bounds.extend(pos);
            pos = new google.maps.LatLng(<?php echo $aankomstlat ?>, <?php echo $aankomstlong ?>);
    overlay = new CustomMarker(pos, map, 'marker_RJAA', 'some name');
    overlay.setMap(map);
        bounds.extend(pos);

      var flightPath = new google.maps.Polyline({path: [new   
google.maps.LatLng(vertreklat, vertreklong),new google.maps.LatLng(<?php echo $aankomstlat ?>, <?php echo $aankomstlong ?>)], strokeColor: '#ffffff', strokeOpacity: 0.7, strokeWeight: 2, geodesic: 
true });
      flightPath.setMap(map);



  map.fitBounds(bounds);google.maps.event.addListener(map, 'zoom_changed', 
function() {
      if(map.getZoom()<2) {
        map.setZoom(2); 
        }
    });
}
$(document).ready(function() {
    initialize();
});
</script>
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • i brought it out of the php block with the ?> and it still seems incorrect. when i look at the html code after the page is refreshed i get (, ) –  Sep 08 '13 at 23:12
  • Are the variable names correct? In comments to the other answer you mention `$row['vertreklong']`, but your question suggests they're just `$vertreklong` (except you left out the `$`). Which is it? – Barmar Sep 08 '13 at 23:15
  • my sql code gives me lh.longitudedecimal AS vertreklong.. so when I "echo" this I would assume it is $row['vertreklong'] is it not? –  Sep 08 '13 at 23:23
0

You can use short echo open tag:

<script>
var foo = <?=$foo?>;
console.log(foo);
</script>

or use AJAX

Yukulélé
  • 15,644
  • 10
  • 70
  • 94