Use php to populate javascript array

醉酒当歌 提交于 2019-12-06 00:15:18

PHP executes on the server before getting sent to the the client. Therefor, if you can do things like this:

newpoints[0] = new Array(<?php echo $lattitude;?>, <?php echo $longitude;?>, icon0, 'Place', 'Content to open');

Where $lattitude and $longitude are values that you pulled out of you database with PHP.

When this page is requested by the client, your php code executes, real values get plugged in where those php tags are making it look like the example you provided, and then it gets sent to the client.

If you want to change these values using JS on the client, or fetch new ones from the server, let me know and I'll add an example of that.

EDIT:

Okay, in light of your comments, it sounds like you've got a few options. Here's one:

When the user selects a category (restaurants, bars, etc) you pass that category as a url parameter and reload either the whole page, or just the map part of it (depends on your set up but might be worth investigating). Your link would look something like this:

http://www.your-domain-here.com/maps.php?category=bars

Maps.php is ready to catch the category using the $_GET array:

$category = $_GET['category']; //'bars'

Your php then grabs the appropriate location data from the database (I'll leave that part to you) and sticks it in a variable that your JS-controlled map will be able to use:

//JS in maps.php  -  you could add this var to the window object
// if you have separated js files...
var locationCoords = <?php echo json_encode($arrayOfCoordinatesFromDB);?>;

When you page loads on the client machine, it now has an array of coordinates to use for the map ready to go in the locationCoords variable.

Then, depending on which coordinates you need to display on the map, you pass them as arguments to your addPoints() using standard Javascript (nothing tricky here).

That's how I'd do it. Hope that helps!

An easy and clean way to pass an array from PHP to JavaScript is to simply echo the json_encode version of the array.

$array = array(1,2,3,4,5,6);
echo 'var values = '.json_encode($array).';';

It is as simple as echoing the php values.
new Array(<?php echo $php_lat;?>, <?php echo $php_long;?>, icon0 etc...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!