How to pass array values from PHP to JavaScript? - javascript

Okay. So i've been here all day, reading and following all the solutions about this topic but i got nothing. Nothing works. Can you show me how to do it, with complete and understandable example. Im new to JavaScript and PHP, so how can i get array values from a PHP file to JavaScript. I tried doing this: var locations = <?php echo json_encode($location); ?>; but i gives me error. and no one answered why. This code here:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 400px;"></div>
<script type="text/javascript">
var locations = [
['Municipal Hall', 6.414333734068895, 125.61093270778656, 1],
['Camarillo Household', 6.4345278, 125.58975, 2],
['Perez Household', 6.4343889, 125.59202777777777, 3],
['Usman Household', 6.4338056, 125.59191666666666, 4],
['Lim Household', 6.4333889, 125.59419444444444, 5]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(6.40, 125.60),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
</body>
</html>
i want to change the value of variable locations from the value from my database. so i got this PHP file:
<?php
$servername = "host";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql='SELECT a.Household_Name, b.Latitude, b.Longitude FROM household a, location b WHERE a.Household_ID = b.Household_ID;';
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
// output data of each row
for($i=0;$i<mysqli_num_rows ( $result );$i++){
$row=mysqli_fetch_row($result);
$location[]= array($row[0].', '.$row[1].', '.$row[2].','.($i+1));
//echo "Household Name: " . $row[0]. " - Latitude: " . $row[1]. " - Longitude " . $row[2]. " " .($i+1)."<br>";
}
}else{echo "0 results";}
?>
it works fine. it outputs the data from the database. now what i want to know is how can i convert that value from the database to a value i can use in place of the locations variable so that the markers will appear on the map? var locations = <?php echo json_encode($location); ?>; this guy give me error, i followed every instruction i can, but still it's error. can u modify my code so that it works or can u just point me out in the WORKING/FUNCTIONAL code there is to your knowledge. Please, help me. I'm in deep trouble here.

Try to change location[] variable from :
$location[]= array($row[0].', '.$row[1].', '.$row[2].','.($i+1));
to
$location[]= array($row[0],$row[1],$row[2],($i+1));
I have added full code below and its working :
<?php
$servername = "host";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql='SELECT a.Household_Name, b.Latitude, b.Longitude FROM household a, location b WHERE a.Household_ID = b.Household_ID;';
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
// output data of each row
for($i=0;$i<mysqli_num_rows ( $result );$i++){
$row=mysqli_fetch_row($result);
$location[]= array($row[0],$row[1],$row[2],($i+1));
//echo "Household Name: " . $row[0]. " - Latitude: " . $row[1]. " - Longitude " . $row[2]. " " .($i+1)."<br>";
}
}else{echo "0 results";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 400px;"></div>
<script type="text/javascript">
/*var locations = [
['Municipal Hall', 6.414333734068895, 125.61093270778656, 1],
['Camarillo Household', 6.4345278, 125.58975, 2],
['Perez Household', 6.4343889, 125.59202777777777, 3],
['Usman Household', 6.4338056, 125.59191666666666, 4],
['Lim Household', 6.4333889, 125.59419444444444, 5]
];*/
var locations = <?php echo json_encode($location); ?>;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(6.40, 125.60),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
</body>
</html>

Your array is not "realy" an array
if your code is :
$location[]= array($row[0].', '.$row[1].', '.$row[2].','.($i+1));
I think the result will be somthing like this :
<script type="text/javascript">
var locations = [["Municipal Hall, 6.414333734068895, 25.61093270778656, 1"],["Camarillo Household', 6.4345278, 125.58975, 2"],......];
.....
</script>
try with :
$location[]= array($row[0],$row[1],$row[2],($i+1));
Edit:
I don't recommend to use this mean to pass PHP array to JS beacause it overload the html page and navigator can't cahe the content of your array. the beter way to do this is to use Ajax function at the page loading with this http://api.jquery.com/jquery.ajax/

Related

Loading latitude/longitude from MySQL database and showing point on Google Maps using PHP,html and JavaScript

I googled a lot but all the solutions i found didn't work for me (even google maps tutorial). I have a MySQL database where I store latitude and longitude values in Float type columns. I wrote php script which connects to the database and selects those values. The idea is that php script passes an array of longitude and latitude values to JavaScript and then Javascript iterate on that array making new markers on Google Maps. Here is my actual code:
<html>
<head>
<style>
#map {
width: 100%;
height: 700px;
background-color: grey;
}
</style>
</head>
<body>
<?php
$query ="SELECT latitude,longitude FROM markers";
$result_array=Array();
$con = new mysqli($host, $user, $password, $dbname, $port)
or die ('Could not connect to the database server' . mysqli_connect_error());
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$latitude=$row['latitude'];
$longitude=$row['longitude'];
$result_array[]=array('latitude'=>$latitude,'longitude'=>$longitude);
}
$json=json_encode($result_array);
$con->close();
?>
<h3>MyMap</h3>
<div id="map"></div>
<script>
function initMap() {
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv, {
center: {lat: 41.5400 , lng: 12.2500},
zoom: 6
});
var array="<?php echo $json_array;?>";
for(var i=0;i<array.length;i++){
var myLatLng=new google.maps.LatLng(lat,lon);
var marker=new google.maps.Marker({
map:map,
position: myLatLng,
});
//}
}
</script>
<script async defer
src=MY GOOGLE API MAP>
</script>
</body>
</html>
Can anyone help me or suggest other ways to do the same thing?
Try putting newlines between <?php and the actual content, like so:
var array=JSON.parse("<?php
echo $json_array;
?>");
The PHP substitution should put the double quotes on the same line.
<html>
<head>
<style>
#map {
width: 100%;
height: 700px;
background-color: grey;
}
</style>
</head>
<body>
<?php
$query ="SELECT latitude,longitude FROM markers";
$result_array=Array();
$con = new mysqli($host, $user, $password, $dbname, $port)
or die ('Could not connect to the database server' . mysqli_connect_error());
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$latitude=$row['latitude'];
$longitude=$row['longitude'];
$result_array[]=array('latitude'=>$latitude,'longitude'=>$longitude);
}
$json=json_encode($result_array);
$con->close();
?>
<h3>MyMap</h3>
<div id="map"></div>
<script>
function initMap() {
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv, {
center: {lat: 41.5400 , lng: 12.2500},
zoom: 6
});
var array="<?php echo $json;?>";//here changed
for(var i=0;i<array.length;i++){
var myLatLng=new google.maps.LatLng(lat,lon);
var marker=new google.maps.Marker({
map:map,
position: myLatLng,
});
//}
}
</script>
<script async defer
src=MY GOOGLE API MAP>
</script>
</body>
</html>

Retrieving values from a php service in HTML

I am trying to build a website that displays a google map with a user location (lat/long) from a php service that I wrote.
I already have a php script that gets the lat/long from a mobile app (via POST from the client), stores it in a DB, and read it back from the DB into two variables, let's call them $lat and $long. To make sure I have the right values in $lat and $long, I did a simple echo and got the two values.
I am struggling with understanding how to read these values from my index.html script. All the examples that I have seen suggest keeping the php code in the html file but I would rather keep them separate. I am also not sure how to assign these values to parameters in HTML/Javacript so I can actually display them on the map.
So my questions are: 1. how do I call that php file from HTML? 2. and how do I read $lat and $long from the php service and assign them to parameters in HTML/Javascript that I can display on the map?
EDIT: here is my PHP code and my index.html (Which is a 1:1 copy from the Google Maps v3 docs).
location.php:
$content = file_get_contents('php://input');
$post_data = json_decode($content , true);
$lat = $post_data['lat'];
$long = $post_data['long'];
//CONNECT TO MYSQL
$con1 = mysql_connect("localhost", "xxxxx", "yyyy", "zzzzz");
if ($con1->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
if (!empty($lat)) {
$sql = "INSERT INTO LocationInfo (latitude, longitude)
VALUES ('$lat', '$long');";
mysql_query($sql) or die ('Error updating database: ' . mysql_error());
}
$read_query = "SELECT * FROM LocationInfo;";
$results = mysql_query($read_query) or die ('Error reading from database: ' . mysql_error());
$column = array();
while($row = mysql_fetch_array($results)){
$column[] = $row;
}
$current_lat = $column[sizeof($column) - 1]['latitude'];
$current_long = $column[sizeof($column) - 1]['longitude'];
echo $current_lat;
echo $current_long;
?>
index.html:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>My GeoLocation</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 14
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
The easiest way to get those variables in Javascript is to output them from PHP to JS, there is no direct bridge, so you will need in the HTML output a script block with the values you got from your SQL query, it will be something like this:
<script>
var lat = <?php echo $lat ?>;
var long = <?php echo $long ?>;
</script>
Now you can use this variables in your javascripts to invoke the map, as a note you can add the variables definition to your main JS block as well.
EDIT:
Rename index.html to index.php
<?php include_once('location.php') ?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>My GeoLocation</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
var map;
function initialize() {
// var myLatlng = new google.maps.LatLng(<?php echo $lat ?>,<?php echo $long ?>);
var mapOptions = {
zoom: 14
//mapTypeId: google.maps.MapTypeId.ROADMAP
//center: myLatlng
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});

Adding multiple markers to Google Maps with JavaScript and PHP

I am having difficulties adding multiple markers to my Google Map. Below is my code:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
function initialize() {
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(-35.3075,149.1244)
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<?php
$dbc = mysql_connect('localhost', 'username', 'password') or die('Unable to connect to MySQL: '.mysql_error());
mysql_select_db ('database', $dbc) or die('Unable to connect to database: '.mysql_error());
$query = "SELECT * FROM centenary_events WHERE location != ''";
$result = mysql_query($query) or die("Error querying database: ".mysql_error());
while ($row = mysql_fetch_array($result)) {
?>
<script>
var link = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.placefinder%20where%20text%3D"<?php echo $row['location']?>"&format=json&diagnostics=true';
$.getJSON(link, function(json) {
console.log("<?php echo $row['title']?>");
console.log("Latitude: " + json.query.results.Result.latitude);
console.log("Longitude: " + json.query.results.Result.longitude);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(Number(json.query.results.Result.latitude), Number(json.query.results.Result.longitude)),
map: map,
title: 'Hello World!'
});
});
</script>
<?php
}
?>
</head>
<body>
<div id="map-canvas" style="width: 100%; height: 100%"></div>
</body>
</html>
Using PHP and MySQL, I am attempting to loop through a database to gather values, and then use those values to add markers to a map. The map is working, but the marker functionality is not. Please help.
You're not doing it in the way you need to :),
So to add multiple marker or what ever into map from php, the best way would be while proccesing the php fetch those data you wanna display and send them to javascript (json,xml or whatever js can parse) or playing with ajax (which is one level higher the this solution), in your case should be like the follow:
HTML&PHP
<?php
$dbc = mysql_connect('localhost', 'username', 'password') or die('Unable to connect to MySQL: '.mysql_error());
mysql_select_db ('database', $dbc) or die('Unable to connect to database: '.mysql_error());
$query = mysql_query("SELECT * FROM centenary_events WHERE location != ''");
$myData = array();
while($row = mysql_fetch_array($result)){
$myData = $row;
}
?>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
//here is the magic :)
var myData = <?php echo json_encode($myData) ?>;
function initialize() {
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(-35.3075,149.1244)
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//and you must set this code here because the map is just initialed
$.each(myData, function(){
var link = 'generate your link here with myData array';
$.getJSON(link, function(json) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(Number(json.query.results.Result.latitude), Number(json.query.results.Result.longitude)),
map: map,
title: 'Hello World!'
});
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
...
The code may have errors, I just wanted to create you an idea how it should look

Using values from mysql database to place marker on googlemaps

Im trying to pull values from mysql database and use to draw a marker on the map but it doesnt seem to work, I've tested the database connection and its working fine but i dont know what the problem is
<html>
<?PHP
include("config.php");
$sql="SELECT * FROM lat long";
$rs = mysqli_query($con,$sql) or die(mysql_error());
$array=mysqli_fetch_array($rs);
$Lat=$array['lat'];
$Lng=$array['long'];
?>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
#select_route {width:20%;height:200px;}
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var map = "";
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(30, 31),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
function addMarker() {
var LatLong= new google.maps.LatLng(<?php echo lat ?> ,<?php echo lng ?>);
//Problem Lies here in passing the lat and long i suppose
marker = new google.maps.Marker({
position:LatLong,
});
marker.setMap(map);
var infowindow = new google.maps.InfoWindow({
content: "<p style='color:blue'>UserInfo</p>" + '<button type="button">Navigate</button>' + '<IMG BORDER="0" ALIGN="Left" SRC="testpic.png">' ,
position: new google.maps.LatLng(30, 31),
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
};
</script>
<div id ="welcome" style="color:#0000FF">
<h3>Welcome to GoogleMaps </h3>
</div>
</head>
<body onload="initialize();addMarker();">
<div id="map_canvas" style="width:60%; height:80%"></div>
First thing that I saw is that you are missing the $ sign before the php variables in the following line:
var LatLong= new google.maps.LatLng(<?php echo lat ?> ,<?php echo lng ?>);
Also the variable names are not correct. You defined the variables as $Lng and $Lat starting with capital letters but in the above code you are using lowercase.
So change that line to:
var LatLong= new google.maps.LatLng(<?php echo $Lat ?> ,<?php echo $Lng ?>);
Besides this, you might have to adjust your query. It would make more sense if it was something along these lines:
"SELECT * FROM table_name" where table_name is the name of your table.
Finally, if it still does not work please post the javascript errors form your browser's console and the php error log to make it easier for me to see the errors.

connecting with DB

I did what you advised, map is displayed correctly, but have no markers. Maybe I've made some mistakes?
Code:
`
mysql_connect("xxx", "xxx", "xxx") or die("Error connecting to database: ".mysql_error());
mysql_select_db("xxx") or die(mysql_error());
$querz = "SELECT * FROM markers";
$result = mysql_query($querz)
or die("Query failed");
while ($row = mysql_fetch_array($result)) {
$lat = "$row[lat]";
$lng = "$row[lng]";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="iso-8859-2">
<title>Simple icons</title>
<style>
html, body, #map-canvas {
height: 600px;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(52, 19)
}
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var image = '20_blue.png';
var myLatLng = new google.maps.LatLng(<?php print($lat); ?>,<?php print($lng); ?>);
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
/html>`
my question: is there any way to display markers from Mysql database instead of use specific lat and lng , like I did in the code above ? How ? I tried google tutorials but it had some bugs (I' ve already asked another question about it).
You need a server side language to connect to your database (in your case I advise you to use PHP which is the simplest). You will be able to select your datas from the database with PDO.
Edit:
You need to write your php loop inside your javascript code. Here you are adding only one marker to your map, the last one you selected with your query. Also make sure the table is not empty.
You can do something like that:
<script type="text/javascript">
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(52, 19)
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var image = '20_blue.png';
<?php while($row = mysql_fetch_array($result)): ?>
var myLatLng = new google.maps.LatLng(<?php echo $row['lat']; ?>, <?php echo $row['lon']; ?>);
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image
});
<?php endwhile; ?>
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
call lat and long from DB and assing them to
$lat
$long
and then you can call them like
var myLatLng = new google.maps.LatLng(<?php print($lat); ?>,<?php print($long); ?>);
This is just an idea, you can turn it as per your needs.

Categories