Rob
Rob

Reputation: 6380

Placing PHP within Javascript

I can't seem to get the PHP to echo out within a Javascript tag:

places.push(new google.maps.LatLng("<?php echo the_field('lat', 1878); ?>"));

What am I doing wrong?

Upvotes: 0

Views: 168

Answers (5)

lugte098
lugte098

Reputation: 2309

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 ;

Upvotes: -1

pixelbreaker
pixelbreaker

Reputation: 56

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.

Upvotes: 1

Martin Bean
Martin Bean

Reputation: 39439

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));
    }
});

Upvotes: 0

aziz punjani
aziz punjani

Reputation: 25796

Have you tried it without the quotes ?

places.push(new google.maps.LatLng(<?php echo the_field('lat', 1878); ?>));

Upvotes: 2

Olli
Olli

Reputation: 752

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.

Upvotes: 2

Related Questions