I’m trying to pass a value via PHP to a Javascript function but it isn’t working, the value doesn’t appear to be going through. When I replace the variable with static text, it works fine.
I’m calling the function via a PHP file like so..
<?php
if (!empty($data['geocode'])) {
echo '<body onload="initializeGM(\'' . $data['geocode'] . '\');">';
} else {
echo '<body>';
}
?>
$data['geocode'] contains both the lat and lng as a string.
Here is the Javascript code..
function initializeGM(geocode) {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(geocode),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
I have added an alert(geocode) into the JS function to test and it works fine.
How can I make it so I can pass the geocode variable in and it works?
Assuming I’ve understood your question correctly,
geocodeis a PHP variable and you want to pass that into a JavaScript function call. If that’s the case, you need toechoout the value of the PHP variable:However, note that the
LatLngconstructor expects 2 arguments of type Number (and an optional boolean argument), and you are only trying to pass in one argument. Although I may have completely misunderstood your intentions.Edit (see comments)
I didn’t notice that you were passing
geocodeas an argument to theinitializeGMfunction. If you were actually trying to pass your PHP variable into that function you need to modify the call to the JavaScript function to use the PHP variable:The above “however” paragraph still applies though. Your code is likely to throw an error as
lngwill beundefinedin theLatLngconstructor function.Edit again (see edited question)
What you have appears at first glance that it should result in something along these lines (as you’ve stated that
geocodecontains a string):There is nothing wrong with that in theory (a string will be passed into
initializeGM) but the problem is that the function expects two arguments of type Number, not one argument of type String:That would require a change to the JavaScript function: