I am trying to call JavaScript function with parameter that are PHP variables. I have tried 2 approaches.
calling JavaScript function in PHP with script tags in echo i.e
<?php echo '<script>initialize('.$lat.','.$lang.','.$zom.');</script>'; ?>
assigning PHP variables values to JavaScript variables
<script> var lat="<?php echo $lat;?>"; var lang="<?php echo $lang; ?>"; var zoom="<?php echo $zoom; ?>"; alert(lat+lang+zoom); initialize(lat,lang,zoom); </script>
In first case function is called as I cross-checked from page source but parameters passed are undefined. And in 2nd case values are successfully saved in JavaScript variables, check it by alert(), but function is not called.
Here is the whole code:
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<?php
if( isset($_POST['lat']) && isset($_POST['lang']) && isset($_POST['zoom']) && isset($_POST['city'])):
$lat=$_POST['lat'];
$lang=$_POST['lang'];
$zoom=$_POST['zoom'];
$city=$_POST['city'];
$zom=(int)$zoom;
var_dump($lang);
var_dump($lat);
//var_dump($zoom);
var_dump($zom);
//echo '<script>initialize('.$lat.','.$lang.','.$zom.');</script>';
endif;
?>
<script>
var lat="<?php echo $lat; ?>";
var lang="<?php echo $lang; ?>";
var zoom="<?php echo $zoom; ?>";
alert(lat+lang+zoom);
initialize(lat,lang,zoom);
</script>
<script>
function initialize(a,b,zom){
if (!a || !b ||!zom){
alert('came on not' +a+b +zom);
// var centerLoc=new google.maps.LatLng( 33.61701054652337,73.37824736488983);
zoom=16;
}
else
{
alert('came');
var zoom =parseInt(zom);
var centerLoc=new google.maps.LatLng(a,b);
}
var mapProp = {
center:centerLoc,
zoom:zoom,
//mapTypeId:google.maps.MapTypeId.ROADMAP
mapTypeId:google.maps.MapTypeId.SATELLITE
};
var map=new google.maps.Map(document.getElementById("googleMap") ,mapProp);
marker=new google.maps.Marker({
position:centerLoc,
title:'Click to zoom'
});
google.maps.event.addListener(marker,'click',function() {
map.setZoom(map.getZoom()+1);
map.setCenter(marker.getPosition());
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body style= "background-color:gainsboro;">
<form method="POST" action="myPage.php" >
Enter latitude: <input type ="text" name="lat" id="lat" / ><br/>
Enter longitude: <input type ="text" name="lang" id="lang"/ ><br/>
Enter City Name: <input type="text" name="city" id="city"/><br/>
Enter Zoom level: <input type ="text" name="zoom" id="zoom"/ ><br/>
<input type="button" value ="Perview" onclick=" initialize(
document.getElementById('lat').value,
document.getElementById('lang').value,
document.getElementById('zoom').value)"/>
<input type="Submit" value="Save" />
</form>
<center><div id="googleMap" style="width:1000px;height:500px;"></div></center>
</body>
</html>