0

I am having some trouble casting a PHP variable to JS. I need to get Lat and Long for a google map, however it will not work with the following code:

PHP (Wordpress):

$lat = get_post_meta( $post->ID, 'lat', true );
$long = get_post_meta( $post->ID, 'long', true );

The Script:

<script type="text/javascript>
    var LatVar = '<?php echo $lat; ?>';
    var LngVar = '<?php echo $long; ?>';
    var myLatLng = {lat: LatVar, lng: LngVar};
</script>

If i insert the Lat and Long manually the map works. I have tested that the PHP get the variables correctly, since when using echo $lat or print_r($lat)` i get the correct data e.g. 9.916599

1
  • Turn on error_reporting(); Additionally, what do you get with console.log(LatVar); in JavaScript? Commented Nov 30, 2015 at 18:15

1 Answer 1

2

I guess the lat and long variables should be floating points.So try removing the quotes.

So your code should be :

<script>
var LatVar = <?php echo $lat; ?>;
var LngVar = <?php echo $long; ?>;

var myLatLng = {lat: LatVar, lng: LngVar};
</script>

Also, I recommend you checking the source code of the rendered page to see if the php echos the variable values there ( with or without quotes. If it is rendering with quotes removing them may fix the issue ). If this is not helping you, get us more details.

PS:- I believe you are using a *.php extension for your file ( Even big programmers make that mistake ).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.