getting variables queried from php to javascript - javascript

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.

Related

How to access array data from PHP in JavaScript [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 7 years ago.
I have this code in PHP. i works fine:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tsunami_simulation";
// 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){
for($i=0;$i<$num_rows;$i++){
$row=mysql_fetch_row($result);
$location[]= $row[0].', '.$row[2].', '.$row[1].','.($i+1);
//echo "Household Name: " . $row[0]. " - Latitude: " . $row[1]. " - Longitude " . $row[2]. " " .($i+1)."<br>";
}
}else{echo "0 results";}
?>
now, what i want to do is access the array result from this PHP file in javascript. i tried using JSON.parse(). but i doesn't work.
i used this piece of code: var locations = '<?php echo json_encode($location); ?>'; i does not give errors. followed by locations = JSON.parse(locations) and it returns <?php echo json_encode($location); ?> this and not the data. how can i get the proper data, any methods will do as long as it works, please help me. btw, i want to get the array from database in wamp and put markers on googlemap using the coordinates from the array. help me please!..
EDIT: There's is the other code where i have to access the data:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>New 1 -- Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?v3"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 400px;"></div>
<?php include 'Location.php';?>
<script type="text/javascript">
var locations = <?php echo json_encode($location, JSON_HEX_TAG); ?>;
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++) {
loc_array = locations[i].split(",");
marker = new google.maps.Marker({
position: new google.maps.LatLng(loc_array[1], loc_array[2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(loc_array[0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
</body>
</html>
$location[]= array($row[0], $row[2], $row[1], $i+1);
and then
var locations = <?php echo json_encode($location, JSON_HEX_TAG); ?>
Note: no JSON.parse needed, no quotes, and especially not manual concatenation of variables to form a quasi-array.
EDIT: JSON_HEX_TAG is highly recommended, if you have PHP 5.3.3+, as plain json_encode is not quite secure.

getting javascript variable value from php array

My javascript is populating markers on map and for that i need locations ,which i have generated from php file in the format given below
i want to dynamically get the result of the php array in the javascript array
<script type="text/javascript">
var locations = /// i want here the output as shown below from the php file
var locations = [["Vidyasagar","28.6139391","77.20902120000005"],
["Pushpadantsagar","21.4598","80.195"],
["Tarunsagar","28.638","77.2936"],
["Samyaktbhushan","20.593684","78.96288000000004"],
["Pavitrasagar","23.2836","79.2318"],
["Prayogsagar","23.2836","79.2318"],
["Arunsagar","30.016","77.4"]];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: new google.maps.LatLng(23.2836,79.2318),
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>
and the php file is this
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "jainmunilocator";
$connection=mysqli_connect($servername, $username, $password, $dbname);;
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
$array = array();
$sql = "SELECT name,id,lat,lng FROM muni_location,munishri WHERE mid=id AND lat<>0";
$result=mysqli_query($connection,$sql);
$i=0;
while($row = mysqli_fetch_assoc($result)){
if(isset($row)){
$array[$i][0]=$row['name'];
$array[$i][1]=$row['lat'];
$array[$i][2]=$row['lng'];
$i++;
}
}
echo json_encode($array);
?>
You will need to use an ajax call. Here is a question on Stack Overflow that has some examples of an ajax call to a php page.
Keep in mind though that you'll need to either include a jQuery library for you to do that, or you can follow along in this question to make an ajax call without jQuery.
You could use PHP to output the variables into a hidden input field's value attribute and encode them as JSON. Then, using Javascript use JSON.parse to decode the PHP variables from the hidden input field's value attribute. You can then remove the element from the DOM.
The trick is by echoing the PHP var into javascript. As Php is processed before, outputting correct Js.
<script>
var locations = array(<?= $VAR ?>);
</script>
In this case $VAR must be something like $VAR = "'barcelona','madrid','london'";
Adjust $VAR so it generate correct output. No need to use JSON encode if you just need it for this.

Reading variables in HTML from a php service

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", "francesco", "bbbbbb", "location111");
if ($con1->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$db_selected = mysql_select_db('location111');
if(mysql_select_db('location111')) { echo 'true '; } else { echo 'falise'; }
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 myLatlng = new google.maps.LatLng(40.7127840,-74.0059410);
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.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
First of all, if you want to display something in template with php, it must have .php extension, not .html
You can then use your php inside of inline javascript like that:
<script type="text/javascript">
var long = "<?php echo $long;?>";
var lat= "<?php echo $lat;?>";
</script>
Or you can use Ajax on other hand

Google map custom marker based on database

In 2 weeks I explored much about Google maps. I am try read a forum and tutorial. But I got this problem when I am going to develop a GIS web. I am using Google maps apiv3, postgre database, and php. I have so much row in my database. Now I only can show multiple marker based on my database, but what I after is the marker have a unique icon based on column content in database like a type 1 = 1.png type 2 = 2.png. the problem is the type is too many, so it is impossible to definition them by manual (because so many type, I already have about 30 type of content in database column ) . I get database value using json. I've already try read forum and some tutorial, but I can't find the answer. sorry for my bad english. please help me, thanks.
this is the code index.php and json.php :
<html lang="en">
<head>
<script type="text/javascript">
function initialize(){
var peta;
var gambar_tanda;
gambar_tanda = 'assets/images/enseval.jpg';
var x = new Array();
var y = new Array();
var customer_name = new Array();
var rayon_name = new Array();
// posisi default peta saat diload
var lokasibaru = new google.maps.LatLng( -1.2653859,116.83119999999997);
var petaoption = {
zoom: 5,
center: lokasibaru,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
peta = new google.maps.Map(document.getElementById("map_canvas"),petaoption);
var infowindow = new google.maps.InfoWindow({
content: ''
});
// memanggil function ambilpeta() untuk menampilkan koordinat
url = "json.php";
$.ajax({
url: url,
dataType: 'json',
cache: false,
success: function(msg){
for(i=0;i<msg.enseval.customer.length;i++){
x[i] = msg.enseval.customer[i].x;
y[i] = msg.enseval.customer[i].y;
customer_name[i] = msg.enseval.customer[i].nama_customer;
//rayon_name[i] = msg.enseval.customer[i].nama_rayon
var point = new google.maps.LatLng(parseFloat(msg.enseval.customer[i].x),parseFloat(msg.enseval.customer[i].y));
tanda = new google.maps.Marker({
position: point,
map: peta,
icon: gambar_tanda,
clickable: true
});
bindInfoWindow(tanda, peta, infowindow, msg.enseval.customer[i].nama_customer );
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function bindInfoWindow(tanda, peta, infowindow, data) {
google.maps.event.addListener(tanda, 'click', function() {
infowindow.setContent(data);
infowindow.open(peta, tanda);
});
}
</script>
<?php
require ('config.php');
$rayon = $_POST['rayon'];
$cabang = $_POST['org_id'];
//echo "$rayon, $cabang, $rayonhasil";
$sql = "SELECT distinct org_id, customer_name, attribute16, attribute17 FROM hasilgis";
$data = pg_query($sql);
$json = '{"enseval": {';
$json .= '"customer":[ ';
while($x = pg_fetch_array($data)){
$json .= '{';
$json .= '"id_customer":"'.$x['org_id'].'",
"nama_customer":"'.htmlspecialchars($x['customer_name']).'",
"x":"'.$x['attribute17'].'",
"y":"'.$x['attribute16'].'"
},';
}
$json = substr($json,0,strlen($json)-1);
$json .= ']';
$json .= '}}';
echo $json;
?>
I'm not sure what's the problem :)
The only thing you must do is to generate icons for all types. You don't have to do it manually - just create a scipt that will generate icons of different colors for every type and name it like 1.jpg, 2.jpg, ...
Pass type via your json message and than on client side create icon url dynamically:
gambar_tanda = 'assets/images/'+msg.enseval.customer[i].type+'.jpg';

Fetch data from database and use it to make markers in Google Maps

I am new to Javascript. I want to fetch lat-long from MySQL (more then 100) and use it to add markers on Google Maps.
To do this I think i've to use php -server side programming. I am able to pass array from PHP to Javascript. Here it is
<?
mysql_connect('localhost', 'username', 'pwd') or die(mysql_error());
echo "Connected to MySQL<br />";
mysql_select_db("pro_user") or die(mysql_error());
$result = mysql_query("SELECT * FROM info");
$no=count($result);
$i=0;
while($row = mysql_fetch_array( $result ))
{
$a[$i]=$row['city'];
$b[$i]=$row['loc_lat'];
$c[$i]=$row['loc_long'];
$i++;
}
?>
<html>
<head>
<script type="text/javascript">
function initialize()
{
var latlng = new google.maps.LatLng(22.3038945, 70.8021599);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<? for($i=0;$i<count($a); $i++)
{
echo "a[$i]='".$a[$i]."';\n";
echo "b[$i]='".$b[$i]."';\n";
echo "c[$i]='".$c[$i]."';\n";
}
?>
function createMarker(latitude,longitude,title)
{
var markerLatLng = new google.maps.LatLng(latitude,longitude);
var marker = new google.maps.Marker({ position: markerLatLng, map: map, title: title });
}
createMarker(22.3038945, 70.8021599,'Gujarat');
for(i=0;i<a.length;i++)
{
document.write(a[i]);
document.write(b[i]);
document.write(c[i]);
initialize().createMarker(b[i], c[i], a[i]);
}
}
</script>
</head>
<body onload="getData()"></body>
</html>
Now I am stuck. I am not able to pass Javascript array to make markers.
There is a very simple tutorial on the google maps website for doing this using PHP / XML / MySQL and Javascript ....
http://code.google.com/apis/maps/articles/phpsqlajax.html

Categories

Resources