I try to get deeper into Leaflet + MySQL Connection, but I'm start loosing the overview. I have a database geomarkers with multiple markers, which have stored different attributes. I want to apply a functionality for the user, to delete markers which are not of interest by clicking "delete" in the marker's Popup-Box. But here its getting complicated. How can I get the individual id (from database) for the marker which is selected (click on delete in PopUp), and how can I pass this to a PHP-Command, that this point will be deleted in the database? I used The $_Post method to upload the data, but in this case thinks wont work.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7/leaflet.css"/>
<link rel="stylesheet" href="http://leaflet.github.io/Leaflet.draw/leaflet.draw.css"/>
<link type="text/css" rel="stylesheet" href="http://fonts.googleapis.com/css?family=Norican">
</head>
<body>
<div id="map" >
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<!--<script type="text/javascript" src="assets/bootstrap/js/bootstrap.min.js"></script>-->
<script src="http://cdn.leafletjs.com/leaflet-0.7/leaflet.js"></script>
<script src="http://leaflet.github.io/Leaflet.draw/leaflet.draw.js"></script>
<script>
$(document).ready(function() {
getUsers();
});
var map = L.map('map').setView([47.000,-120.554],13);
mapLink =
'OpenStreetMap';
L.tileLayer(
'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
attribution: 'Map data: © OpenStreetMap contributors, SRTM | Map style: © OpenTopoMap (CC-BY-SA)',
maxZoom: 18,
}).addTo(map);
var greenIcon = L.icon({
iconUrl: 'http://leafletjs.com/examples/custom-icons/leaf-green.png',
iconSize: [30, 38], // size of the icon
});
function getUsers() {
$.getJSON("getData.php", function (data) {
for (var i = 0; i < data.length; i++) {
var location = new L.LatLng(data[i].lat, data[i].lng);
var id = data[i].id;
var species = data[i].species;
var diameter = data[i].average_diameter;
var quality = data[i].quality;
var damage = data[i].damage;
var notes = data[i].additional_information;
var marker = L.marker([data[i].lat, data[i].lng], {icon: greenIcon}).addTo(map);
marker.bindPopup(id + "<br>" + species + "<br>" + diameter + "<br>" + quality + "<br>" + damage + "<br>" + notes + "<br>" + "<br>" +
'<input type="submit" id = "delete" name="action" data-value = " + id + " value="Delete" method = "post"/>');
}
})
}
</script>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#delete').click(function(d){
var id = document.getElementById("delete").getAttribute("data-value");
$.ajax({
type: 'POST',
url: 'delete.php',
data: {id:id}
success: function(data) {
alert(data);
}
error: function(data){
alert('Something went wrong while deleting.');}
});
});
});
</script>
</script>
</body>
</html>
getData.php
<?php
$connect = mysqli_connect("localhost", "root", "", "useraccounts");
$sql = "SELECT * FROM geomarker";
$result = mysqli_query($connect, $sql);
$json_array = array();
while($data = mysqli_fetch_assoc($result))
{
$json_array[] = $data;
}
echo json_encode($json_array);
?>
delete.php
<?php
if(isset($_POST)){
$id = $_POST['id'];
$connect = mysqli_connect("localhost", "root", "", "useraccounts");
$sql = "DELETE FROM geomarker WHERE id = ($id)";
$result = mysqli_query($connect, $sql);
if($result){
echo 'Data successfully deleted.';
}else{
echo 'There were erros while deleting the data.';
}
}
?>
If your
'<a href="#" id = "delete" data-value = id >delete</a>'
is in some way winding up calling a function delete() somewhere and passing it the data-value attribute, all you may need to do is to write it so that the actual value of the ID at the point this is being defined is used:
'<a href="#" id = "delete" data-value = "' + id + "' >delete</a>'
#DrSnuggles In this way you can get to the delete function in the popup
marker.on('popupopen', function(e) {
// your delete function
});
Update example
let config = {
minZoom: 7,
maxZomm: 18,
};
const zoom = 16;
const lat = 52.2297700;
const lon = 21.0117800;
let points = [
[52.230020586193795, 21.01083755493164, 'point 1'],
[52.22924516170657, 21.011320352554325, 'point 2'],
[52.229511304688444, 21.01270973682404, 'point 3'],
[52.23040500771883, 21.012146472930908, 'point 4']
];
const map = L.map('map', config).setView([lat, lon], zoom);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
// loop that adds many markers to the map
for (let i = 0; i < points.length; i++) {
const lat = points[i][0];
const lng = points[i][1];
const popupText = `<button data-value="test-${i+1}" class="delete">${points[i][2]}</button>`;
marker = new L.marker([lat, lng])
.bindPopup(popupText)
.addTo(map);
marker.on('popupopen', function(e) {
const btns = document.querySelectorAll('.delete');
btns.forEach(btn => {
btn.addEventListener('click', () => {
alert(btn.getAttribute('data-value'));
})
})
});
}
* {
margin: 0;
padding: 0
}
html {
height: 100%
}
body,
html,
#map {
height: 100%;
margin: 0;
padding: 0
}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.6.0/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.6.0/dist/leaflet.js"></script>
<div id="map"></div>
Final code:
Finally I managed to puzzle everything together, getUsers() get some adjustment:
function getUsers() {
$.getJSON("getData.php", function (data) {
for (var i = 0; i < data.length; i++) {
var location = new L.LatLng(data[i].lat, data[i].lng);
var id = data[i].id;
var species = data[i].species;
var diameter = data[i].average_diameter;
var quality = data[i].quality;
var damage = data[i].damage;
var notes = data[i].additional_information;
var popupText = `<button data-value= "${data[i].id}" class="delete">Delete</button>`;
var marker = new L.marker([data[i].lat, data[i].lng], {icon: greenIcon}).addTo(map);
marker.bindPopup("ID:"+ id + "<br>" + "Species: " + species + "<br>" + "Diameter: " + diameter +"cm" + "<br>" +"Quality: " + quality + "<br>" +"Damage: " + damage + "<br>" +"Notes: " + notes + "<br>" + "<br>" + popupText);
marker.on('popupopen',function(e){
const btns = document.querySelectorAll('.delete');
btns.forEach(btn => {
btn.addEventListener('click', () => {
var id = btn.getAttribute('data-value');
$.ajax({
type: 'POST',
url: 'delete.php',
data: {id1:id},
success: function(data){
alert(data);},
error: function(data){
alert('Something went wrong.');}
});
})
});
});
}
})
}
and also delete.php gets some adjustment:
<?php
$id= $_POST['id1'];
$connect = mysqli_connect("localhost", "root", "", "useraccounts");
$sql = "DELETE FROM geomarker WHERE id = ($id)";
$result = mysqli_query($connect, $sql);
if($result){
echo 'Data successfully deleted.';
}else{
echo 'There were erros while deleting the data.';
}
?>
Thx for the help!
im trying to do the following with my current script:
Saving Google Geo Location Informations in File, when the Visitor clicks "Accept Detection of my location"
Output Google Maps URL with the Information
<!DOCTYPE html>
<html>
<head>
<style>
#tripmeter {
border: 0px double black;
padding: 0px;
margin: 0px 0;
}
p {
color: #222;
font: 14px Arial;
}
span {
color: #00C;
}
</style>
</head>
<body>
<div id="tripmeter">
<p>
Starting Location (lat, lon):<br/>
<span id="startLat">???</span>°, <span id="startLon">???</span>°
</p>
<p>
Current Location (lat, lon):<br/>
<span id="currentLat">???</span>°, <span id="currentLon">???</span>°
</p>
<p>
Distance from starting location:<br/>
<span id="distance">0</span> km
</p>
</div>
<script>
window.onload = function() {
var startPos;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
startPos = position;
document.getElementById("startLat").innerHTML = startPos.coords.latitude;
document.getElementById("startLon").innerHTML = startPos.coords.longitude;
}, function(error) {
alert("Error occurred. Error code: " + error.code);
// error.code can be:
// 0: unknown error
// 1: permission denied
// 2: position unavailable (error response from locaton provider)
// 3: timed out
});
navigator.geolocation.watchPosition(function(position) {
document.getElementById("currentLat").innerHTML = position.coords.latitude;
document.getElementById("currentLon").innerHTML = position.coords.longitude;
document.getElementById("distance").innerHTML =
calculateDistance(startPos.coords.latitude, startPos.coords.longitude,
position.coords.latitude, position.coords.longitude);
});
}
};
// Reused code - copyright Moveable Type Scripts - retrieved May 4, 2010.
// http://www.movable-type.co.uk/scripts/latlong.html
// Under Creative Commons License http://creativecommons.org/licenses/by/3.0/
function calculateDistance(lat1, lon1, lat2, lon2) {
var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
</script>
</body>
</html>
<meta charset="utf-8"/>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
</head>
<body>
<div id="pos" style="width:800px; height:600px;">
Detection Location..
</div>
<script>
function initialize(coords) {
var latlng = new google.maps.LatLng(coords.latitude, coords.longitude);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("pos"), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "You"
});
}
navigator.geolocation.getCurrentPosition(function(position){
initialize(position.coords);
}, function(){
document.getElementById('pos').innerHTML = 'Failed to detect Location.';
});
</script>
<?php
$dns = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$ip = $_SERVER['REMOTE_ADDR'];
$rand2 = time();
$port= htmlspecialchars(
$_SERVER['REMOTE_PORT']);
$browser= htmlspecialchars(
$_SERVER['HTTP_USER_AGENT']);
$ausgabe="• I WANT TO SAVE THE GOOGLE MAPS URL WITH THE DETECTED LOCATION •";
$datum=date("d.m.Y, H:i:s");
$array = file("location.log"); // Datei in ein Array einlesen
array_unshift($array, "".$datum." ".$ausgabe."\n");
$string = implode("", $array);
file_put_contents("location.log", $string);
?>
</body>
</html>
Anyone has a good idea? :)
If you want to save the longitude and latitude into a file (please check the Google API terms of usage if you are even allowed to do that), you have to get the coordinates first, then send them to your server via AJAX.
The below examples are not "copy/paste" material, since I didn't try them out. Use them as a general guideline.
First, you need to create a script, that will get the coordinates:
<html>
<head>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>
<div id="pos" style="width:800px; height:600px;">
Detection Location..
</div>
<script>
$(function(){
function initialize(coords) {
$.ajax({
url: 'saveLocation.php',
data: {
longitude:coords.longitude,
latitude:coords.latitude
},
error: function() {
$('#pos').html("Could not save location");
},
success: function(data) {
$('#pos').html("Location saved successfully");
},
type: 'POST'
});
}
navigator.geolocation.getCurrentPosition(function(position){
initialize(position.coords);
}, function(){
$('#pos').html('Failed to detect Location.');
});
});
</script>
</body>
</html>
On your server, you need a PHP script ""saveLocation.php":
<?php
$ausgabe=$_POST['longitude'].":".$_POST['latitude'];
$datum=date("d.m.Y, H:i:s");
$array = file("location.log"); // Datei in ein Array einlesen
array_unshift($array, "".$datum." ".$ausgabe."\n");
$string = implode("", $array);
file_put_contents("location.log", $string);
echo json_encode(array("success"=>"true"));
?>
I used jQuery to simplify some of the regular stuff, like sending data via AJAX or changing the inner HTML of an element.
Again, this code is not in working condition. It will not work if you just copy/paste it
I have been at this some time trying to get highcharts to chart some data returned by php. I have done many searches and nothing works. I can write the php to deliver the data however it needs to be but how do you get it to dynamically chart it?????
I can deliver it as:
[["1372875867","44.8782806"],["1372875885","46.2020226"]]
or
[[1372876686,44.0655823],[1372876693,43.3360596], etc ]
but how do I get the data from the php output into the dyname example they display?????
!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
Highcharts.setOptions({
global : {
useUTC : false
}
});
// Create the chart
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'container',
events : {
load : function() {
// set up the updating of the chart eachsecond
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(),
y = Math.round(Math.random() * 100);
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 0
},
title : {
text : 'Live random data'
},
exporting: {
enabled: false
},
series : [{
name : 'Random data',
data : (function() {
// generate an array of random data
var data = [], time = (new Date()).getTime(), i;
for( i = -999; i <= 0; i++) {
data.push([
time + i * 1000,
Math.round(Math.random() * 100)
]);
}
return data;
})()
}]
});
});
</script>
</head>
<body>
<script src="../../js/highstock.js"></script>
<script src="../../js/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>
my current php is:
<?php
// include("$_SERVER[DOCUMENT_ROOT]/config/config.php");
include("adodb5/adodb.inc.php");
$connection = new COM("ADODB.Connection") or die("Cannot start ADO");
$result_set = $connection->Execute("
SELECT tag, TIME, value
FROM picomp
WHERE TIME >= '*-3m' AND tag = 'xxx:xx_xxx.xxx'
");
$result_count = 0;
// $labels = array();
while (!$result_set->EOF) {
$pidate = date("U", strtotime($result_set->fields[1]) );
if ($result_count <> 0){
print ",";
}else{
print "[";
}
print "[".$pidate.",".$result_set->fields[2]."]";
// array_push("{$result_set->fields[2]}");
$result_count = $result_count +1;
$result_set->MoveNext();
// echo "testing";
}
print "];";
You can use HighchartsPHP which is a wrapper for Highcharts, which basically allows you to write all that JS code in PHP. It's very useful and pretty simple to use.
HighchartsPHP on GitHub
Your timestamp should be multiplied by 1000, and both values should be numbers.
Please familair with soultion, how to prepare JSON, because you only print "as JSON", but it is not.
Take look at http://php.net/manual/en/function.json-encode.php where some examples are introduced.
Hey guys I am having trouble loading my data into the highstock charts.
My json.php calls on a sample MySQL database and looks something like this:
$result = mysql_query("SELECT UNIX_TIMESTAMP(date)*1000 AS timestamp,value from sample") or die('Could not query');
if(mysql_num_rows($result)){
echo 'Test';
$first = true;
$row=mysql_fetch_assoc($result);
while($row=mysql_fetch_row($result)){
if($first) {
$first = false;
} else {
echo ',';
}
$json_str = json_encode($row, JSON_NUMERIC_CHECK);
echo $json_str;
}
if(array_key_exists('callback', $_GET)){
$callback = $_GET['callback'];
echo $callback. '('.$json_str.');';
}
} else {
echo '[]';
}
mysql_close($db);
My index.htm which calls the Json.php is from the sample highstock template I just merely changed the getJson to match with my reference. Here is the code. Any help would be much appreciated, thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$.getJSON('json.php', function(data) {
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : 'Test'
},
series : [{
name : 'Test',
data : data,
marker : {
enabled : true,
radius : 3
},
shadow : true,
tooltip : {
valueDecimals : 2
}
}]
});
});
});
</script>
</head>
<body>
<script src="js/highstock.js"></script>
<script src="js/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>
Also, my json is parsed in this manner:
Test[1370899026000,10],[1370899026000,4],[1368177426000,11],[1370899026000,12],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,9],[1370899026000,14],[1370899026000,12],[1370899026000,10],[1370899026000,15],[1370899026000,12],[1378826226000,7],[1370899026000,9],[1370899026000,11],[1370899026000,7],[1370899026000,3],[1370899026000,6],[1370899026000,0],[1370899026000,11],[1370899026000,5],[1370899026000,9],[1370899026000,7],[1370899026000,8],[1370899026000,8],[1370899026000,9],[1370899026000,13],[1370899026000,11],[1370899026000,10],[1370899026000,13],[1370899026000,12],[1370899026000,12],[1370899026000,11],[1370899026000,13],[1370899026000,10],[1370899026000,8],[1370899026000,15],[1370899026000,13],[1370899026000,12],[1370899026000,14],[1370899026000,9],[1370899026000,9],[1370899026000,12],[1370899026000,13],[1370899026000,4],[1370899026000,4],[1370899026000,4],[1370899026000,13],[1370899026000,5],[1370899026000,10],[1370899026000,4],[1370899026000,10],[1370899026000,22],[1370899026000,9],[1370899026000,5],[1370899026000,9],[1370899026000,10],[1370899026000,5],[1370899026000,7],[1370899026000,10],[1370899026000,5],[1370899026000,7],[1370899026000,9],[1370899026000,9],[1370899026000,10],[1370899026000,6],[1370899026000,6],[1370899026000,6],[1370899026000,12],[1370899026000,7],[1370899026000,12],[1370899026000,8],[1370899026000,13],[1370899026000,12],[1370899026000,9],[1370899026000,7],[1370899026000,7],[1370899026000,9],[1370899026000,12],[1370899026000,13],[1370899026000,9],[1370899026000,10],[1370899026000,4],[1370899026000,11],[1370899026000,12],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,9],[1370899026000,14],[1370899026000,12],[1370899026000,10],[1370899026000,15],[1370899026000,12],[1370899026000,7],[1370899026000,9],[1370899026000,11],[1370899026000,7],[1370899026000,3],[1370899026000,6],[1370899026000,0],[1370899026000,11],[1370899026000,5],[1370899026000,9],[1370899026000,7],[1370899026000,8],[1370899026000,8],[1370899026000,9],[1370899026000,13],[1370899026000,11],[1370899026000,10],[1370899026000,13],[1370899026000,12],[1370899026000,12],[1370899026000,11],[1370899026000,13],[1370899026000,10],[1370899026000,8],[1370899026000,15],[1370899026000,13],[1370899026000,12],[1370899026000,14],[1370899026000,9],[1370899026000,9],[1370899026000,12],[1370899026000,13],[1370899026000,4],[1370899026000,4],[1370899026000,4],[1370899026000,13],[1370899026000,5],[1370899026000,10],[1370899026000,4],[1370899026000,10],[1370899026000,22],[1370899026000,9],[1370899026000,5],[1370899026000,9],[1370899026000,10],[1370899026000,5],[1370899026000,7]
Try closing with
[]
Highstock fiddle: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/stock/demo/areaspline/
Data of that fiddle: http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
Please take look at http://docs.highcharts.com/#preprocessing-data-from-a-database and take look at very simple example with json_encode:
tmp = array();
$tmp[] = array('A',5);
$tmp[] = array('B',6);
$tmp[] = array('C',1);
$tmp[] = array('D',2);
$rows = array();
for($i=0; $i<count($tmp); $i++)
{
$row['name'] = $tmp[$i][0];
$row['data'] = array($tmp[$i][1]);
array_push($rows,$row);
}
print json_encode($rows);
Highcharts:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
series: [{
name: 'Browser share',
data: []
}]
}
$.getJSON("datavotecolum.php", function(json) {
console.log(json);
options.series = json;
chart = new Highcharts.Chart(options,function(chart){
console.log(chart.series);
});
});
});