Placing PHP within Javascript
I can't seem to get the PHP to echo out within a Javascript开发者_如何学Go tag:
places.push(new google.maps.LatLng("<?php echo the_field('lat', 1878); ?>"));
What am I doing wrong?
Have you tried it without the quotes ?
places.push(new google.maps.LatLng(<?php echo the_field('lat', 1878); ?>));
PHP works when you execute the page, and it should work.
Please note that php does not execute when you run a JS function.
Please also make sure that you really have that the_field
function.
I suspect you have your " quotes in the LatLng method arguments when there shouldn't be any.
Your php should output a string such as '50.123123123, 12.123144' (without the ' quotes). The LatLng method expects 2 values.
places.push(new google.maps.LatLng(<?php echo the_field('lat', 1878); ?>));
Try that.
If you're looking to populate a Google Map with markers as the result of a database query, you probably want to wrap it in a JSON web service. Something as simple as:
<?php
// file to query database and grab palces
// do database connection
$places = array();
$sql = "SELECT * FROM places";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$places[] = $row;
}
header('Content-Type: application/json');
echo json_encode($places);
exit;
And then in your JavaScript file:
// get places
$.getJSON('getplaces.php', function(response) {
for (var i = 0; i < response.length; i++) {
place[] = response[i];
places.push(new google.maps.LatLng(place.lat, place.lng));
}
});
If i understand what you are trying to do (maybe some more explanation of your problem is required for this), then this might be your answer:
places.push(new google.maps.LatLng(<?php echo '"' . the_field('lat', 1878) . '"' ?>));
EDIT: removed the ;
精彩评论