Just want to pass php variables $x and $y to javascript map function (as lat and long). Please help.
Here is my controller:
<?php
$x = 25.114667;
$y = 55.137797;
?>
Here is my JS file:
function initialize()
{
var myCenter = new google.maps.LatLng(lat,long);
var mapOptions = {
center:myCenter,
zoom:12,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap")
,mapOptions);
} google.maps.event.addDomListener(document.getElementById('showhidemap'), 'click', initialize);
you are passing string in you js variable lat and long. assign value directly as float
try this
var lat = <?php echo $x; ?>;
var long = <?php echo $y; ?>;
also must include the script with google map key on above of google map initialization.
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=GOOGLE_MAP_KEY&sensor=true"> </script>
GOOGLE MAP KEY : must be generate for your site.
see some urls might help you
https://developers.google.com/maps/tutorials/fundamentals/adding-a-google-map
https://developers.google.com/maps/signup?csw=1
https://developers.google.com/maps/documentation/javascript/tutorial
did you try to add
$x = 25.114667;
$y = 55.137797;
to some tag like
<div data-lat="<?php echo $y; ?>" data-long="<?php echo $y; ?>" id="showhidemap">show map</div>
You need to create a Javascript object in your .php file, just before your include your javascript file (the one containing the above fragment), which will be filled by your longitude/latitude information.
Like this:
YOUR PHP FILE
<html>
...
<script type="text/javascript">
var mapLangLat = {
long:<?php echo $x; ?>,
lati:<?php echo $y; ?>
};
</script>
<script src="my_remote_script.js"></script>
...
YOUR JAVASCRIPT FILE
<script>
function initialize()
{
var lat = window.mapLangLat.lati;
var long = window.mapLangLat.long;
...
It's required to find the PHP part above to be able to code that little javascript object.
Related
I'm having a problem trying to use a PHP variable within JavaScript. I keep getting the following message.
"Invalid or unexpected token. Message: Undefined variable: example."
I'm unsure why example is being undefined, as it is defined within the php code. Here is my code:
<?php
$example = '2';
?>
<script type="text/javascript">
var php_var = "<?php echo json_encode($example); ?>";
</script>
Does anyone have any suggestions? I have also tried the following javascript that results in the same problem:
<script type="text/javascript">
var php_var = "<?php echo $example; ?>";
</script>
Firstly, your original code has a syntax error: $example = '2' needs a semicolon.
Secondly, the next piece of code is just assigning the string <?php echo $example; ?> to the JavaScript variable php_var where the $example PHP variable is first substituted. The $example variable should be initiated properly first, however, for this to work.
As a separate note: JS cannot execute PHP directly -- only a PHP server can do so. What you're most likely trying to do is this:
<?php
$example = '2';
?>
<script type="text/javascript">
var php_var = '<?php echo $example ;?>';
</script>
This should work, use single quotes
<?php
$example = '2';
?>
<script type="text/javascript">
var php_var = '<?php echo $example; ?>';
</script>
Tried and working both variant:
<?php
$example = '2';
?>
<script type="text/javascript">
var php_var = <?php echo json_encode($example); ?>;
console.log(php_var);
</script>
<script type="text/javascript">
var php_va = "<?php echo $example; ?>";
console.log(php_va);
</script>
I'm creating one Graph chart using Google APIs I used Java Script source from Google. In PHP I'm using while loop where I fetch some array row using query, this mysql query works fine, and values of fetched array are also correct (When I echoed that in PHP) but problem is that how do I pass this values to JavaScripts function?
My PHP code is as follows :
while ($graph_result = mysqli_fetch_row($graph))
{
$graphCount = $graph_result[0];
$graphMonth = $graph_result[1];
echo $graphCount; // This works
echo $graphMonth;
}
This gives me in result of two rows, each contains two values listed below:
Now I want to pass this above values to Java script function so that it draws Graph chart for me, my javascript code is as follows:
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[graphMonth, graphCount] // Here I have to place PHP values !
]);
}
So how to pass this values to JS ???
Try the below code,
In PHP
$i = 0;
while ($graph_result = mysqli_fetch_row($graph))
{
$graph_values[$i]["count"] = $graph_result[0];
$graph_values[$i]["month"] = $graph_result[1];
$i++;
}
In script,
<script>
<?php foreach($graph_values as $key){ ?>
drawChart('<?php echo $key["count"]; ?>', '<?php echo $key["month"]; ?>');
<?php } ?>
function drawChart(graphCount, graphMonth) {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[graphMonth, graphCount]
]);
}
</script>
<?php while ($graph_result = mysqli_fetch_row($graph))
{
?>
<script>
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[<?php echo $graph_result[0]; ?>, <?php echo $graph_result[1]; ?>]
]);
}
</script>
<?php
}
?>
I don't know if it is best practice or not..
You can use json to do that.
In your while loop, build an associative array and encode it in json:
$jsonArray = array();
while ($graph_result = mysqli_fetch_row($graph))
{
$graphCount = $graph_result[0];
$graphMonth = $graph_result[1];
$jsonArray[] = array($graphCount, $graphMonth);
}
echo '<div id="json">' . json_encode($jsonArray) . '</div>';
And then recover it in your javascript:
var json_data = JSON.parse(document.getElementById('json').innerHTML);
function drawChart(json_data) {
var data = google.visualization.DataTable();
data.addColumn('number','Months');
data.addColumn('number','users');
data.addRows(json_data);
}
Trying a new method of plotting a marker on google map with my lat/long queried from a data base. when i create variables within the jquery script tag, it works but im not able to make a call outside out that script. But when i try to set those variables with a json_encode from the php array outside of that script, the console returns with
Uncaught SyntaxError: Unexpected token < index:html:29
<!DOCTYPE html>
<html>
<head>
<style>
#map {
width: 1200px;
height: 900px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js">></script>
<script type = "text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(38.4403, -122.5463);
var mapOptions = {
zoom: 10,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title:"Hello World!"
});
marker.setMap(map);
}
var latitude = <?php echo json_encode($lat);?>;
var longitude = <?php echo json_encode($long);?>;
var LatLong = new google.maps.LatLng(latitude, longitude);
var marker1 = new google.maps.Marker({
position: LatLong;
title:"Test"
});
marker1.setMap(map);
</script>
</head>
<body onload = "initialize()">
<div id="map"></div>
</body>
</html>
PHP to query over database:
<?php
require("server_info.php");
$connection=db2_connect($database, $username, $password);
if (!$connection) { die('Not connected : ' . db2_conn_error());}
$query = "SELECT lat,long FROM SCHOOL";
$stmt = db2_prepare($connection, $query);
$result = db2_execute($stmt);
$lat = array();
$long = array();
while ($row = db2_fetch_array($stmt)) {
$lat = $row[0];
$long = $row[1];
}
//echo json_encode($lat);
//echo json_encode($long);
db2_close($connection);
?>
The problem is that your file is named index.html. By default, only files with .php suffix are executed using PHP. Since it has a .html extension, the webserver is just returning the file verbatim to the browser, instead of running it through PHP, so <?php echo json_encode($lat); ?> is sent to the client, and that's not valid Javascript.
You should rename it to index.php, then it will be executed using PHP, and the variables will be substituted.
But it looks like there's more to the problem than this. You never set the variables $lat and $long anywhere in the script. You're setting them in a completely different script.
What you probably should be doing is using AJAX to call the query script from Javascript.
I need to pass the value of the variable php to javascript but I can not.
Try many forms and does not work.
work with the following versions and not whether the cause of the failure.
Apache 2.2.25 and PHP 5.2.17 (I need to work For Now With These Versions).
The value that should receive the variable in the example is "kml/Aechmea_magdalenae.kml"
$anio = $row['kml_map'];
<script>
function initialize() {
var mexico = new google.maps.LatLng(20.6568241,-103.3984801);
var mapOptions = {
zoom: 11,
mapTypeId: google.maps.MapTypeId.TERRAIN,
center: mexico
}
var url2 = <?php echo json_encode($anio) ?>;
var url1 = 'http://www.cnf.gob.mx:8090/snif/especies_forestales/';
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var ctaLayer = new google.maps.KmlLayer({url: url1+url2});
ctaLayer.setMap(map);}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
As you can see here, echoing a json_encoded url string will escape the forward slashes in that url.
The solution then is either to do:
var url = '<?php echo $anio; ?>';
Making sure that the value of $anio does not contain any single quotes, or (if you're running PHP 5.4 or up), to use this:
var url = <?php echo json_encode($anio, JSON_UNESCAPED_SLASHES); ?>;
Note the lack of quotes (json_encode will add quotes for you), and the use of the JSON_UNESCAPED_SLASHES constant. check the manual for more constants
demo/PoC here
Look this line:
var url2 = <?php echo json_encode($anio) ?>;
If you intend to json_encode (i think is the other way), you should use quotes, some like
var url2 = "<?php echo json_encode($anio) ?>";
I'm somewhat new to Javascript but know enough that I'm aware I shouldn't be writing my Javascript inline with my HTML but instead loading it from an external file. I've been trying to put it in an external file, but because of the way my code works I think it would be better to arrange it in functions that can be called at various points. What is the best practice for this?
At a guess, I'd say I should be wrapping all the JS in a singular file and then calling each code fragment with a function... but I'm not entirely sure how to do that and I'm not knowledgeable enough to know how to pose the question to look around online.
Here's a sample:
<html>
<script type="text/javascript"> <!--Create the arrays-->
var locationLat = new Array();
var locationLong = new Array();
var postURL = new Array();
var postExcerpt = new Array();
var postTitle = new Array();
var featImg = new Array();
var i = 0;
</script>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<script type="text/javascript"> <!--Load data from Wordpress into the arrays so we can use them on a map later-->
locationLat[i] = "<?php echo get_post_meta( get_the_ID(), 'locationLat', true ) ?>";
locationLong[i] = "<?php echo get_post_meta( get_the_ID(), 'locationLong', true ) ?>";
postURL[i] = "<?php echo get_permalink( $id );?>";
postExcerpt[i] = "<?php echo get_the_excerpt();?>";
postTitle[i] = "<?php echo get_the_title($ID);?>";
featImg[i] = "<?php echo wp_get_attachment_url(get_post_thumbnail_id($post->ID)); ?>"
i++;
</script>
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>
<script type="text/javascript">
function initialize() { <!--**I tried putting this function into an external JS file and calling it onLoad with body but it didn't do anythin**g-->
google.maps.visualRefresh = true;
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(37.09024,-95.712891),
disableDefaultUI: true,
};
var posts = locationLat.length;
var j = 0;
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var place = new Array();
while (posts != j)
{
var image = '<?php echo get_template_directory_uri(); ?>/location_marker.png';
var myLatLng = new google.maps.LatLng(locationLat[j],locationLong[j]);
place[j] = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
url: postURL[j],
excerpt: postExcerpt[j],
title: postTitle[j],
cover: featImg[j]
});
google.maps.event.addListener(place[j], 'click', function() {
map.panTo(this.getPosition());
map.setZoom(8);
$('#spantext').html(this.title);
$('#poste').html(this.excerpt);
$('.fillme').html('<img src="' + this.cover + '">');
$('.readmore').html('<p>Read more >');
$('.sidebar').show().stop().animate({
'width' : '400px',
'opacity' : '1'
}, 500);
});
j++;
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body>
If I'm completely off track, some guidance would be good. Everything works in this format but I really don't think it's correct. I'm aware this is a relatively dumb question, but in lieu of finding a really good answer anywhere I thought it was worth asking.
I would suggest to put the different piceces of js into different files & add them with php.
But for that, first tailor the js to be independent chunks i.e one piece of js should not be accessing variables from another.
So it would look something like :
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<script type="text/javascript" src="myScript.js">
</script>
Contents of myScript.js
<!--Load data from Wordpress into the arrays so we can use them on a map later-->
locationLat[i] = "<?php echo get_post_meta( get_the_ID(), 'locationLat', true ) ?>";
locationLong[i] = "<?php echo get_post_meta( get_the_ID(), 'locationLong', true ) ?>";
postURL[i] = "<?php echo get_permalink( $id );?>";
postExcerpt[i] = "<?php echo get_the_excerpt();?>";
postTitle[i] = "<?php echo get_the_title($ID);?>";
featImg[i] = "<?php echo wp_get_attachment_url(get_post_thumbnail_id($post->ID)); ?>"
i++;