Having divs act as button objects to retrieve data - javascript

I populated a list using the following code.
I'm trying to make each of the objects retrieved from the server act like a button and when clicked throw a pop up box displaying address, date, and status. Is there anyway to do this? I've been looking into using Ajax but it is getting a little confusing as I have an html file and a php file that has all my javascript/php (the javascript relies on a php function) and from what I've read I would need to make another php file to service the request. How then would I reference it within my html file to do so? I may be making this harder than it needs to be.
Original Code:
<?php
function getjson(){
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, lng, lat FROM information WHERE username = '" . $_SESSION['user_name'] . "';";
$result = $db_connection->query($sql);
$temp = array();
while($row = $result->fetch_assoc()) {
$temp[] = $row;
}
$db_connection->close();
$json = json_encode($temp);
return $json;
}
function getwarnings(){
$username = $_SESSION['user_name'];
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, date, id, address, status FROM information WHERE username = '" . $username . "';";
$result = $db_connection->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
switch($row["status"]){
case 3:
echo '<div id= "content" style = "background-color: red" onclick = popinformation(' . $row["id"] . ')> ' . $row["address"] . "</div>";
break;
case 4:
echo '<div id= "content" style = "background-color: yellow" onclick = popinformation(' . $row["id"] . ')> ' . $row["address"] . "</div>";
break;
case 5:
echo '<div id= "content" style = "background-color: green" onclick = popinformation(' . $row["id"] . ')> ' . $row["address"] . "</div>";
break;
}
}
}
$db_connection->close();
}
function getalerts($id){
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, date, id, address, status FROM information WHERE id = '" . $id . "';";
$result = $db_connection->query($sql);
$temp = array();
$row = $result->fetch_assoc();
$temp[] = $row;
$db_connection->close();
return json_encode($temp);
}
?>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script>
function getlocations(){
var data = <?php echo getjson(); ?>;
var i = 0;
var locations = new Array();
for(i; i < data.length; i++){
var dataholder = [data[i].misc, parseFloat(data[i].lat), parseFloat(data[i].lng)];
locations.push(dataholder);
}
return locations;
}
function createmap(){
var locations = getlocations();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: new google.maps.LatLng(47.624561, -122.356445),
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));
}
}
function popinformation(data){
var json = <?php getalerts(); ?>
console.log(json);
}
Update:
Here's what I was trying, from what I've read I have a misunderstanding of php/javascript. This is all my code within the file. Colors appear fine but pop-ups do not appear, Console reports Uncaught SyntaxError: Unexpected token < which will go away if I delete the final script. I think that means the error is within the echo json_encode($results) somehow.
<?php
function getjson(){
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, lng, lat FROM information WHERE username = '" . $_SESSION['user_name'] . "';";
$result = $db_connection->query($sql);
$temp = array();
while($row = $result->fetch_assoc()) {
$temp[] = $row;
}
$db_connection->close();
$json = json_encode($temp);
return $json;
}
function getwarnings(){
$username = $_SESSION['user_name'];
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, date, id, address, status FROM information WHERE username = '" . $username . "';";
$result = $db_connection->query($sql);
$colors = array(3 => 'red', 4 => 'yellow', 5 => 'green');
$results = array();
while ($row = $result->fetch_assoc()){
$results[$row['id']] = $row;
echo '<div class="content" style = "background-color: ' . $colors[$row['status']] . '" data-id="' . $row["id"] . '"> ' . $row["address"] . "</div>";
}
$db_connection->close();
}
function getalerts($id){
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT date, id, address, status FROM information WHERE id = '" . $id . "';";
$result = $db_connection->query($sql);
$temp = array();
while($row = $result->fetch_assoc()) {
$temp[] = $row;
}
$db_connection->close();
$json = json_encode($temp);
return $json;
}
?>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script>
function getlocations(){
var data = <?php echo getjson(); ?>;
var i = 0;
var locations = new Array();
for(i; i < data.length; i++){
var dataholder = [data[i].misc, parseFloat(data[i].lat), parseFloat(data[i].lng)];
locations.push(dataholder);
}
return locations;
}
function createmap(){
var locations = getlocations();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: new google.maps.LatLng(47.624561, -122.356445),
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>
<script>
$(document).ready(function() {
var information_object = <?php echo json_encode($results); ?>;
$(".content").click(function() {
var info = information_object[$(this).data('id')];
if (info) {
alert("Address: " + info.address + "\nDate: " + info.date + "\nStatus: " + info.status);
} else {
alert("Invalid ID: " + id);
}
});
});
My html Document
<html>
<head>
<link rel="stylesheet" href="css/logged_in.css">
<?php
include("login_php_scripts.php");
?>
</head>
<body>
<div id="navigation">
Account
Logout
</div>
<div id="header">
<div id="logo"></div>
<div id="header_text"></div>
</div>
<div id="content_wrapper">
<div id="list_view">
I am logged in as: <?php echo $_SESSION['user_name']; ?></br>
<?php
getwarnings();
?>
</div>
<div id="map">
<script>
createmap();
</script>
</div>
</div>
<div id="footer"></div>
</body>
</html>

Put all the database results into an array, then convert that to a Javascript object that your popup function can look up by ID.
function getwarnings(){
$username = $_SESSION['user_name'];
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, date, id, address, status FROM information WHERE username = '" . $username . "';";
$result = $db_connection->query($sql);
$colors = array(3 => 'red', 4 => 'yellow', 5 => 'green');
$results = array();
while ($row = $result->fetch_assoc()){
$results[$row['id']] = $row;
echo '<div class="content" style = "background-color: ' . $colors[$row['status']] . '" data-id="' . $row["id"] . '"> ' . $row["address"] . "</div>";
}
$db_connection->close();
?>
<script>
$(document).ready(function() {
var information_object = <?php echo json_encode($results); ?>;
$(".content").click(function() {
var info = information_object[$(this).data('id')];
if (info) {
alert("Address: " + info.address + "\nDate: " + info.date + "\nStatus: " + info.status);
} else {
alert("Invalid ID: " + id);
}
});
});
</script>
<?php
}

Related

Setting location markers for each location on google map

I have code that I'm using (I didn't write it myself) that creates a Polyline on top of a google map based on lon and lat entries I have in my DB. It's working well right now. I'd like to add a marker for each location that makes up the line on the map so I can click on it and see the time, lon and lat info from the DB record for that point.
Here is the current code:
<?php
function flightpath($days = 1) {
if (($days > 100) || ($days < 1) || (!is_numeric($days))) {
echo 'Please specify a correct number of days (maximum 100 days)';
return;
}
$flightpath_part[0] = "<script>
function initialize() {
var myLatLng = new google.maps.LatLng(";
$flightpath_part[1] = ");
var mapOptions = {
zoom: 11,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var flightPlanCoordinates = [
";
$flightpath_part[2] = "
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 3
});
flightPath.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
echo 'Connection with MySQL database failed!';
exit();
}
$query = "SELECT `log`, `lat`, `lon` FROM `location` WHERE `log` >= ( DATE_SUB( CURDATE( ), INTERVAL " . ($days -1) . " DAY ) ) AND user_id = '$user_idA' ORDER BY `log` ASC";
$result = mysqli_query($conn, $query);
$rowcount = mysqli_num_rows($result);
if ($rowcount == 0) {
echo "<br /><br /><br /><center><p>You have no locations in your database for this period!</p></center>";
} else {
$lat_sum = 0;
$lon_sum = 0;
$loc_sum = 0;
$flightpath = '';
while ($line = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
foreach ($line as $col_value) {
$lon = $line['lon'];
$lat = $line['lat'];
$lon_sum = $lon_sum + $lon;
$lat_sum = $lat_sum + $lat;
$loc_sum = $loc_sum + 1;
if ($lon && $lat) {
$flightpath .= " new google.maps.LatLng(";
$flightpath .= $line['lat'];
$flightpath .= ", ";
$flightpath .= $line['lon'];
$flightpath .= "),\r\n";
}
}
}
$lon_center = $lon_sum / $loc_sum;
$lat_center = $lat_sum / $loc_sum;
$flightpath = substr_replace($flightpath, "", -3);
$flightpath = $flightpath_part[0] . $lat_center . ', ' . $lon_center . $flightpath_part[1] . $flightpath . $flightpath_part[2];
}
mysqli_close($conn);
return $flightpath;
}
?>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=visualization"></script>
<?php echo flightpath($days); ?>
Since the database has the lon and lat coordinates stored you can use those to create the map markers. You could try something like:
function flightmarkers($days=1){
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
echo 'Connection with MySQL database failed!';
exit();
}
$query = "SELECT `log`, `lat`, `lon` FROM `location` WHERE `log` >= ( DATE_SUB( CURDATE( ), INTERVAL " . ($days -1) . " DAY ) ) AND user_id = '$user_idA' ORDER BY `log` ASC";
$result = mysqli_query($conn, $query);
$rowcount = mysqli_num_rows($result);
if ($rowcount == 0) {
echo "<br /><br /><br /><center><p>You have no locations in your database for this period!</p></center>";
} else {
$flightmarkers= '';
while ($line = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
foreach ($line as $col_value) {
$lon = $line['lon'];
$lat = $line['lat'];
if ($lon && $lat) {
$flightmarkers.=
'marker = new google.maps.Marker({
position: new google.maps.LatLng('.$line['lat'].','.$line['lon'].'),
map: map
});
';
}
}
return $flightmarkers;
}
<?php echo flightpath($days); ?>
<?php echo flightmarkers($days); ?>
I can't test it and I wasn't sure of the point of *_sum vars considering they are statically set to 0 so they dont really do anything. I removed them for simplicity. This might at least get you started in the right direction.
This link has a good bit of info about map markers also Google Maps JS API v3 - Simple Multiple Marker Example

Transfer json array from PHP to JS

I am trying to transfer a json array from PHP to JS
<?php
//controllo se sono presenti i parametri
if(isset($_GET['id_utente']) && isset($_GET['longitude']) && isset($_GET['latitude']))
{
//Recupero il valore dei parametri
$id_utente = $_GET['id_utente'];
$longitude= $_GET['longitude'];
$latitude = $_GET['latitude'];
}
$servername = "localhost";
$username = "realegr";
$password = "pass";
$dbname = "my_realegr";
// Create connection,
$conn = mysqli_connect($servername, $username, $password,$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully\n";
// Insert Data
$sql = "INSERT INTO Prova (id_utente, latitude, longitude)
VALUES ('" . $id_utente . "', '" . $longitude . "', '" . $latitude . "')
";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully\n\r";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
// Execute query and save it in result
$sql = "SELECT latitude,longitude FROM Prova ORDER by reg_date DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
//if (mysqli_num_rows($result) > 0) {
// output data of each row
/* while($row = mysqli_fetch_assoc($result)) {
echo "latitude: " . $row["longitude"]. " - longitude: " . $row["latitude"]. "<br>";
}
} else {
echo "0 results";
}
*/
$row = mysqli_fetch_assoc($result);
echo json_encode([
'status' => true,
'latitude' => $row["longitude"],
'longitude' => $row["latitude"],
]);
mysqli_close($conn);
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBkEtPH07_xBVh8dWBzCQYtWimkOUnPGMQ&callback=initMap"></script>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script>
function initMap(){
var $request = $.get('http://realegr.altervista.org/PopolamentoTabella.php');
$request.done( function(data) {
alert(data);
var pasedData = JSON.parse(data);
var longi = parseFloat(pasedData.longitude);
var lati = parseFloat(pasedData.latitude);
var uluru = {lat: lati, lng: longi};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
})
}
</script>
</body>
</html>
The php script seems work well.It updates the DB and echo the JSON array,as it should.
But when I try to load the Maps it gives me some error:
Beside in console I have this:
further information:evry time I send data to DB( with a get request), the php script has to send (only)gps coordinates to JS,to show them on a google maps
Change your 'PopolamentoTabella.php' to this
<?php
$servername = "localhost";
$username = "YOURUSERNAME";
$password = "YOURPASSWORD";
$dbname = "YOUR DB";
// Create connection,
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//echo "Connected successfully\n";
//controllo se sono presenti i parametri
if (isset($_GET['id_utente']) && isset($_GET['longitude']) && isset($_GET['latitude'])) {
//Recupero il valore dei parametri
$id_utente = $_GET['id_utente'];
$longitude = $_GET['longitude'];
$latitude = $_GET['latitude'];
// Insert Data
$sql = "INSERT INTO Prova (id_utente, latitude, longitude)
VALUES ('" . $id_utente . "', '" . $longitude . "', '" . $latitude . "')
";
if (mysqli_query($conn, $sql)) {
//echo "New record created successfully\n\r";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
} else {
// Execute query and save it in result
$sql = "SELECT latitude,longitude FROM Prova ORDER by reg_date DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
//if (mysqli_num_rows($result) > 0) {
// output data of each row
/* while($row = mysqli_fetch_assoc($result)) {
echo "latitude: " . $row["longitude"]. " - longitude: " . $row["latitude"]. "<br>";
}
} else {
echo "0 results";
}
*/
$row = mysqli_fetch_assoc($result);
echo json_encode([
'status' => true,
'latitude' => $row["longitude"],
'longitude' => $row["latitude"],
]);
}
//echo $longitude;
mysqli_close($conn);
?>

JavaScript/AJAX prints weirdly

My JavaScript/AJAX prints comments. It's all good, until I want to insert/get more than one comment. It duplicates itself. This feels like a nesting/missed parenthesis problem in my code, but I can't be able to find it...
My JS code:
$(document).ready(function(){
var url = 'comment-get.inc.php';
$.getJSON(url, function(data) {
$.each(data, function(index, item) {
var t = '';
t += '<div class="comment_holder" id="_'+item.id+'">';
t += '<div class="user"> <img src="src/img/page3_img7.jpg" alt="" class="img_inner fleft">';
t += '<div class="extra_wrapper">';
t += ''+item.username+'<br>';
t += ''+item.date+'<br>';
t += '<button class="button2" type="button" id="'+item.id+'">Delete</button>';
t += '</div></div>';
t += ''+item.message+'<br><br>';
t += '</div>';
$('.comment_holder').prepend(t);
add_delete_handlers();
});
});
add_delete_handlers();
$('#postButton').click(function(){
comment_post_btn_click();
});
function comment_post_btn_click()
{
//text in textarea with username, page and date
var _username = $('#postUsername').val();
var _page = $('#postPage').val();
var _date = $('#postDate').val();
var _message = $('#postMessage').val();
if(_message.length > 0)
{
//proceed with ajax callback
$('#postMessage').css('border', '1px solid #ABABAB');
$.post("comment-set.inc.php",
{
task : "comment-set",
username : _username,
page : _page,
date : _date,
message : _message
}
).success(
function(data)
{
//Task: Insert html into the div
comment_set(jQuery.parseJSON(data));
console.log("ResponseText: " + data);
});
}
else
{
//text in area is empty
$('#postMessage').css('border', '1px solid #FF0000');
console.log("Comment is empty");
}
//remove text after posting
$('#postMessage').val("");
}
function add_delete_handlers()
{
$('.button2').each(function()
{
var btn = this;
$(btn).click(function()
{
comment_delete(btn.id);
});
});
}
function comment_delete(_id)
{
$.post("comment-del.inc.php",
{
task : "comment-del",
id : _id
}
).success(
function(data)
{
$('#_' + _id).detach();
});
}
function comment_set(data)
{
var t = '';
t += '<div class="comment_holder" id="_'+data.comment.id+'">';
t += '<div class="user"> <img src="src/img/page3_img7.jpg" alt="" class="img_inner fleft">';
t += '<div class="extra_wrapper">';
t += ''+data.comment.username+'<br>';
t += ''+data.comment.date+'<br>';
t += '<button class="button2" type="button" id="'+data.comment.id+'">Delete</button>';
t += '</div></div>';
t += ''+data.comment.message+'<br><br>';
t += '</div>';
$('.comment_holder').prepend(t);
add_delete_handlers();
}
});
Comments.php:
<?php
class Comments {
public function set($message, $username, $date, $page) {
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "INSERT INTO comments VALUES ('', '$username', '$page', '$date', '$message')";
$query = mysqli_query($connect, $sql);
if($query){
$std = new stdClass();
$std->id = mysqli_insert_id($connect);
$std->message = $message;
$std->username = $username;
$std->date = $date;
$std->page = $page;
return $std;
}
return null;
}
public function del($id) {
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "DELETE FROM comments WHERE id = $id";
$query = mysqli_query($connect, $sql);
if($query)
{
return true;
}
}
}
?>
Comment-get.inc.php:
<?php
$page = htmlentities("/index.php?page=maplepancakes", ENT_QUOTES);
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "SELECT * FROM comments WHERE page='$page' ORDER BY id DESC";
$result = $connect->query($sql);
$data = array();
while ($row = $result->fetch_assoc()) {
$row_data = array(
'id' => $row['id'],
'username' => $row['username'],
'date' => $row['date'],
'message' => $row['message']
);
array_push($data, $row_data);
}
?>
<?php
echo json_encode($data);
?>
Comment-set.inc.php:
<?php
if(isset($_POST['task']) && $_POST['task'] == 'comment-set'){
$username = $_POST['username'];
$date = $_POST['date'];
$page = $_POST['page'];
$message = $_POST['message'];
require_once 'comments.php';
if(class_exists('Comments')){
$userInfo = $username;
$commentInfo = Comments::set($message, $username, $date, $page);
$std = new stdClass();
$std->user = $userInfo;
$std->comment = $commentInfo;
echo json_encode($std);
}
}
?>
Picture of the problem (json_encode in the bottom of the picture containing 3 comments):
your comments div container has class .comment_holder so each time with new comment you prepend to all class's so create comment container with unique id an prepend to this. like this $('#comment_container').prepend(t); this with work.

Google Map is not appearing when connecting to database

I want to retrieve geocodes from a database using PHP and MySQL with JSON. It works by selecting an option from a drop-down list and reading the matching data. I think the functions of PHP and MySQL are working correctly is just some problem with JavaScript and the map.
Code for the JavaScript:
<div data-role="content" id="accommodation">
<div id="Manu">
<select id="Cheltenham"></select>
<!--Map-->
<div id="myMap">
<script type="text/javascript">
/* call the php that has the php array which is json_encoded */
$.getJSON('cheltenham.php', function(data){
/* data will hold the php array as a javascript object */
$.each(data, function(key, val){
var x = document.getElementById("Cheltenham");
var option = document.createElement("option");
option.text = val.BUSTYPE;
option.value = val.REFERENCE;
x.add(option);
})
});
function initialize(){
$(document).on('click', '#Cheltenham', function() {
var referenceID = $(this).selected.value;
$.getJSON('SearchBusinesses.php?ReferenceID='+referenceID, function(data) {
ev_ref = data.REFERENCE;
ev_busid = data.BUSID
ev_name = data.NAME;
lat = parseFloat(data.LATITUDE);
longi = parseFloat(data.LONGITUDE);
});
var map;
var myLatlng = new google.maps.LatLng(lat,longi);
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
var mapOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("myMap"), mapOptions);
showMarker();
function showMarker() {
marker = new google.maps.Marker({
map: map,
position: myLatlng,
draggable: true
});
geocoder.geocode({'latLng': myLatlng }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var marker = new google.maps.Marker({map: map, position:results[0].geometry.location});
infowindow.setContent(ev_name + '<br/>' + lat + '<br/>' + long);
infowindow.open(map, marker);
}
}
});
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</div>
</div>
</div>
Code for cheltenham.php:
<?php
$servername = "localhost";
$username = "secret";
$password = "secret";
$dbname = "secret";
function getEventList(){
global $servername, $username, $password, $dbname;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `BUSINESS_TYPE`";
$result = $conn->query($sql);
$rows = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
} else {
//echo "0 results" . "<br>";
}
$conn->close();
echo json_encode($rows);
}
getEventList();
?>
Code for SearchBusinesses.php
<?php
$servername = "localhost";
$username = "secret";
$password = "secret";
$dbname = "secret";
$evReference = $_GET['REFERENCE'];
function getEventOne(){
global $servername, $username, $password, $dbname, $evName;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT `LATITUDE`, `LONGITUDE` FROM `BUSINESSES` where `REFERENCE` = '" . $evReference . "'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
echo json_encode($row);
} else {
//echo "0 results" . "<br>";
}
$conn->close();
}
getEventOne();
?>
add this line to cheltenham.php
echo json_encode($rows, JSON_FORCE_OBJECT);

Leaflet Show all Markers from Database to Map

First I want to Demonstrate my code before asking my Question.
The code below will show all of my data from Database to my Webpage
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbmarker";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * from tblmarker";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br>",$row["lat"]," &nbsp &nbsp &nbsp &nbsp &nbsp ",$row["lng"] ;
}
} else {
echo "0 results";
}
$conn->close();
?>
and this is the output of my code that will show all of the Lat/Long
14.704659335030026 121.02397441864012
14.704659335030026 121.02397441864012
14.704659335030026 121.02397441864012
14.704659335030026 121.02397441864012
14.704659335030026 121.02397441864012
14.704659335030026 121.02397441864012
14.704659335030026 121.02397441864012
14.704659335030026 121.02397441864012
14.704659335030026 121.02397441864012
My question is how can i connect this output in this code?
var note = document.getElementById('note');
var datepick = document.getElementById('demo1');
var timepick = document.getElementById('timepick');
layerpoly.on('click', function(e){
var markerA = new L.Marker(e.latlng,{icon: Icon1});
markerA.bindPopup("</a><br><strong>FIRE</strong></br><strong>Date:</strong>"+datepick.value+"</br><strong>Time:</strong>"+timepick.value+"</br><strong>Address:</strong>"+note.value+"<strong><br><strong>Suspect Sketch</strong><br><a href=legends/suspect.jpg rel=lightbox><img src = legends/suspect.jpg height=100 width = 100/>").addTo(map);
closure1 (markerA)
Or to simplify my Question, How can i Fetch those outputs and convert them as Leaflet Lat/long of my marker? What will happen is that get the lat/long and put a marker on the map when the webpage finish load. TY
you can create your array within the php data for examples:
$data = array();
echo " var latlong = [ " ;
for ( $x = 0; $x < mysql_num_rows( $query); $x++) {
$data[] = mysql_fetch_assoc( $query);
echo " [ " , $data[ $x][ 'lat' ], " , " , $data[ $x][ 'long' ], " ] " ;
if ( $x <= ( mysql_num_rows( $query) - 2) ) {
echo " , " ;
}
}
echo " ]; " ;
This piece of code adjusted to your fields creates the var latlong and in your case gets the output of:
latlong = [
[14.704659335030026,121.02397441864012],
[14.704659335030026,121.02397441864012],
[14.704659335030026,121.02397441864012],
[14.704659335030026,121.02397441864012],
[14.704659335030026,121.02397441864012],
[14.704659335030026,121.02397441864012],
[14.704659335030026,121.02397441864012],
[14.704659335030026,121.02397441864012],
[14.704659335030026,121.02397441864012]];
Then you simply add your php into the map page like:
<?php include 'latlong.php' ?>
and a function for the points to be displayed like:
for ( var i = 0; i < latlong.length; i ++) {
marker = new L.marker([latlong[i][ 1 ],latlong[i][ 2]])
.addTo(map);
}

Categories