I'm trying to show data from visitors inside a map created using jvectormap plugin.
This is driving me crazy, i can not load the data through ajax, if i put the data manually it works.
So far i have this:
map.php
$datos = array();
$link->set_charset("utf8");
$sql = $link->query("SELECT SUM(ID) as visitors, state FROM visitors WHERE state != '' GROUP BY state");
while($row = $sql->fetch_row()){
$ss = $link->query("SELECT * FROM states WHERE state = '".$row[1]."'");
$rr = $ss->fetch_row();
$datos[] = array("ccode" => $rr[2], "visits" => $row[0]);
}
$data = array("countries" => $datos);
echo json_encode($data,JSON_NUMERIC_CHECK);
This returns the following data:
{"countries":[{"ccode":"VE-A","visits":81},{"ccode":"VE-L","visits":24}]}
Now the function to load the map:
function cargaMapa(){
//jvectormap data
$.post("ajax/map.php",{},function(mapa){
var dataC = eval(mapa);
//var dataC = {"countries":[{"ccode":"VE-A","visits":81},{"ccode":"VE-L","visits":24}]};
var countryData = [];
//for each country, set the code and value
$.each(dataC.countries, function() {
countryData[this.ccode] = this.visits;
console.log("Estado: "+this.ccode+" Visitas: "+this.visits);
});
//World map by jvectormap
$('#world-map').vectorMap({
map: 've_mill_en',
backgroundColor: "#fff",
regionStyle: {
initial: {
fill: '#e4e4e4',
"fill-opacity": 1,
stroke: 'none',
"stroke-width": 0,
"stroke-opacity": 1
}
},
series: {
regions: [{
values: countryData,
scale: ["#3c8dbc", "#2D79A6"], //['#3E5E6B', '#A6BAC2'],
normalizeFunction: 'polynomial'
}]
},
onRegionLabelShow: function(e, el, code) {
//search through dataC to find the selected country by it's code
var country = $.grep(dataC.countries, function(obj, index) {
return obj.ccode == code;
})[0]; //snag the first one
//only if selected country was found in dataC
if (country != undefined) {
el.html(el.html() + ': ' + country.ccode + country.visits + ' visitas');
}
}
});
});
}
As you can see in the function i have the var dataC, if i load in there the array coming from map.php it gives me Uncaught SyntaxError: Unexpected token : but if copy and paste the result of map.php into the var dataC it works pretty good.
How can i solve this?
I appreciate any help
Thanks
I figured it out, just changed $.post for $.getJSON and the magic began
Related
I have this code that gets the data from postgis and but when launching my page my markers won't show, even though there is no error in the console. the problem seemes to come from couche.on('data:loaded', function (e) since apparently it's not able to get the loaded data and because when i do couche.addTo(maCarte) directly the markers show. And i tried it in a another example with var couche = new L.GeoJSON.AJAX("data/markers.geojson", { and it works.
Another problem is when i enter a variable to select a specefic marker i always get the same error Uncaught SyntaxError: Unexpected token < in JSON at position 2 even though i checked my php file and it's fine and show the results when i launched directly Exécution du script PHP it happens in this code only when i add a variable and when there is none and the variable is null, the data is downloaded without any problem, so i don't know where the problem is coming from.
Can anyone please help me find a solution ?
function loadData() {
console.log('php/lecture.php?var=' + variable )
$.ajax({url:'php/lecture.php?var=' + variable ,
success: function(response){
data = JSON.parse(response)
console.log(data)
console.log('Données téléchargées : ' + response.length / 1000000 + 'Mo')
drawEntities(data)
maCarte.fitBounds(couche.getBounds())
}
})
}
couche = new L.GeoJSON(data.features, {
onEachFeature: function (feature, layer) {
layer.bindPopup('<h4>date_debut: ' + feature.properties.date_debut+
'</h4>')
},
pointToLayer: createCircleMarker
});
couche.on('data:loaded', function (e){
function makeGroup(color) {
return new L.MarkerClusterGroup({
iconCreateFunction: function(cluster) {
return new L.DivIcon({
iconSize: [20, 20],
html: '<div style="text-align:center;background:'+color + '">' +
cluster.getChildCount() + '</div>'
});
}
}).addTo(maCarte);
}
var groups = {
TR: makeGroup('red'),
DE: makeGroup('green'),
CA: makeGroup('orange'),
CO: makeGroup('blue')
};
e.target.eachLayer(function(layer) {
groups[layer.feature.properties.type].addLayer(layer);
});
});
}
I have fetched values From my MySQL Database and stored it in JSON Format. Now What I am trying to do is that I need to show those values on the JvectorMap.
but I am not able to do it.
Here is my PHP code :
$json_data=array();
foreach($result as $rec)
{
$json_array['Country']=$rec['user_country'];
$json_array['CountryCode']=$rec['country_code'];
$json_array['persons']=$rec['usercountry'];
array_push($json_data,$json_array);
} echo json_encode($json_data) ;
The JSON That I am recieving is :
[
{"Country":"Australia","CountryCode":"AU","persons":"5"},
{"Country":"Spain","CountryCode":"ES","persons":"2"},
{"Country":"India","CountryCode":"IN","persons":"8"},
{"Country":"Mexico","CountryCode":"MX","persons":"4"},
{"Country":"United States","CountryCode":"US","persons":"4"}
]
The Script that I am using is :
<script type="text/javascript">
var dataC = '<?php echo $data ; ?>' ;
var countryData = {};
$.each(dataC, function() {
countryData[this.CountryCode] = this.persons;
});
$(function() {
$('#world-map').vectorMap({
map: 'world_mill_en',
series: {
regions: [{
values: countryData, //load the data
scale: ['#C8EEFF', '#0071A4'],
normalizeFunction: 'polynomial'}]
},
//-----------------------------------------------
// changed to onRegionLabelShow from onLabelShow
//-----------------------------------------------
onRegionLabelShow: function(e, el, code) {
//search through dataC to find the selected country by it's code
var country =$.grep(dataC, function(obj, index) {
return obj.CountryCode == code;
})[0]; //snag the first one
//only if selected country was found in dataC
if (country != undefined) {
el.html(el.html() +
"<br/><b>Code: </b>" +country.CountryCode +
"<br/><b>Name: </b>" + country.Country +
"<br/><b>persons: </b>" + country.persons);
}
}
});
});
</script>
But I am getting the error :
" jquery.min.js:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"Country":"Australia","CountryCode":"AU","persons":"5"},{"Country":"Spain","CountryCode":"ES","persons":"2"},{"Country":"India","CountryCode":"IN","persons":"8"},{"Country":"Mexico","CountryCode":"MX","persons":"4"},{"Country":"United States","CountryCode":"US","persons":"4"}] "
I'm trying to find method to merge many polygon ( >100 ) in order to have only 1 polygon to have just the border of the merged polygon, not border for all "little" polygon
I import coordinates from JSON file and I use this code to render each polygon:
var thisUcVar<?php echo $nb_fichier ?>;
var thisAgencyVar<?php echo $nb_fichier ?>;
var thisListAgencyVar;
var thisUcColor;
$.getJSON("<?php echo("test/". $fichier); ?>", function(json1) {
var i=0;
var coordUc = [];
var thisUc = json1;
thisUcVar<?php echo $nb_fichier ?> = thisUc[0].name;
thisAgencyVar<?php echo $nb_fichier ?> = thisUc[0].agency;
thisUcColor = thisUc[0].color;
$.each(json1, function(key, data){
i = 0;
$.each(data.coordinates, function(key, data){
coordUc.length = 0;
$.each(data, function(key, data){
var innerCoordUc = {"lat": data[1], "lng": data[0] };
coordUc[i] = innerCoordUc;
i++;
});
var uc = new google.maps.Polygon({
title: i,
strokeWeight: 1,
fillColor: thisUcColor,
paths: coordUc,
zIndex: 10
});
uc.setMap(map);
map.addListener('zoom_changed',function(){
if(map.getZoom()>=10){
uc.set('zIndex', 90);
}else{
uc.set('zIndex', 10);
}
});
uc.addListener('click', function() {
$(".layer").html("<h1>" + thisUcVar<?php echo $nb_fichier ?> + "</h1><ul></ul>");
$.each(thisAgencyVar<?php echo $nb_fichier ?>, function(key, data){
listThisAgencyVar = data.name;
$(".layer").append("<li>" + uc.title + listThisAgencyVar + "</li>");
});
if(map.getZoom() >= 10){
map.setZoom(11);
map.setCenter(uc.getBounds().getCenter());
}
});
if (!google.maps.Polygon.prototype.getBounds) {
google.maps.Polygon.prototype.getBounds=function(){
var bounds = new google.maps.LatLngBounds()
this.getPath().forEach(function(element,index){bounds.extend(element)})
return bounds;
}
}
});
});//fin de boucle json1
});
Result is like image below:
And here one of the JSON files that I'm using to generate each polygons.
JSON used to generate polygons group
I search everywhere and I didn't find any way to merge many polygons in one big ...
Thanks a lot
A solution that might work is using the Turf library. In particular, it has a union method that does exactly what you want (merge multiple polygons into one that corresponds to the union of the polygons).
However, this library uses the Geojson standard format so you will need to convert your data into this standard.
If you can use this format, it will also help you to display the data on the map using a DataLayer and the loadGeoJson method from Google Maps API.
I am trying to update data field with PHP recourd using var point. Here is my PHP code:
$query_Recordset1 = "SELECT * FROM table";
$Recordset1 = mysql_query($query_Recordset1, $egrid) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
$Peak = mysql_result($Recordset1 ,0,"Peak");
print $Peak;
The PHP script does work, however when I attempt to insert it into my .js document nothing happens. Here is my javascript:
series: [{
name: 'Peak Average',
data: [18000], //interval update in Add some life
tooltip: {
valueSuffix: ' Peak'
}
}]
},
// Add some life
function(chart) {
setInterval(
function() {
var point = chart.series[0].points[0], newVal;
$.get("peak.php", function(newVal) {
console.log(newVal, typeof newVal);
point.update(parseFloat(newVal));
});
}
,5000);
});
I have even tried making adjustments as per string versus number:
point.update(newVal);
PLEASE HELP.
It's becoming a nightmare for me solving this problem. I am developing an app using phonegap. I have used highcharts in it for Graphs. The graph is coming properly but not the tooltip in the graph. Please check the code below, I need this code to be able to show the tooltip with proper data. There has to be a loop of the following code and it has to be for every user or series in the graph. So I have ran a for loop in PHP and saved it in a variable and got the whole output of the loop using AJAX in a JSON format.
When I use the variable in the Javascript code in which I have saved the AJAX output, it just doesn't do anything but if I alert than it alerts the exact code which I want to make tooltip work. I have tried eval() also but no benefit. Any help or guidance will be much appreciated.
Loop Code
$toolTip = '';
for($i=0;$i<$teamControllerW->total_user;$i++){
$toolTip .= "var chart = $('#team_containerWF').highcharts();";
$toolTip .= "var figures".$i." = [".join($teamControllerW->new_yAxesData1[$i], ",") ."]; ";
$toolTip .= "var fatVals".$i." = [". join($teamControllerW->fatVal[$i], ',') ."]; ";
$toolTip .= "var weightVals".$i." = [". join($teamControllerW->weightVal[$i], ',') ."]; ";
$toolTip .= "var result_playing_dates = [". join($teamControllerW->new_playing_dates_data[$i], ',') ."]; ";
$toolTip .= "
$.each(figures".$i.", function (j, figure".$i.") {
var curDanger = (figure".$i."[0] - danger[0][0]) * delta + danger[0][1];
var play_date = false;
for (var k = 0; k < result_playing_dates.length ; k ++ ) {
if (figure".$i."[0] == result_playing_dates[k]) {
play_date = true;
break;
}
}
";
$toolTip .= "if (figure".$i."[1] > curDanger) {
if (play_date) {
if (chart.series[".$i."].data[j] && chart.series[".$i."].data[j].graphic) {
chart.series[".$i."].data[j].graphic.attr({ fill: '#a31515' });
chart.series[".$i."].data[j].update({
fatVal : fatVals".$i."[j],
weightVal : weightVals".$i."[j],
marker:{
fillColor: '#a31515',
radius: 6,
states: {
hover: {
fillColor: '#a31515',
lineColor: '#a31515',
radius: 10
}
}
}
});
}
}
else {
if (chart.series[".$i."].data[j] && chart.series[".$i."].data[j].graphic) {
chart.series[".$i."].data[j].graphic.attr({ fill: 'red' });
chart.series[".$i."].data[j].update({
fatVal : fatVals".$i."[j],
weightVal : weightVals".$i."[j],
marker:{
fillColor: 'red',
states: {
hover: {
fillColor: 'red',
lineColor: 'red'
}
}
}
});
}
}
}else{
if (play_date) {
if (chart.series[".$i."].data[j] && chart.series[".$i."].data[j].graphic) {
chart.series[".$i."].data[j].graphic.attr({ fill: '#02491a' });
chart.series[".$i."].data[j].update({
fatVal : fatVals".$i."[j],
weightVal : weightVals".$i."[j],
marker:{
fillColor: '#02491a',
radius: 6,
states: {
hover: {
fillColor: '#02491a',
lineColor: '#02491a',
radius: 10
}
}
}
});
}
}
else {
if (chart.series[".$i."].data[j] && chart.series[".$i."].data[j].graphic) {
chart.series[".$i."].data[j].graphic.attr({ fill: 'green' });
chart.series[".$i."].data[j].update({
fatVal : fatVals".$i."[j],
weightVal : weightVals".$i."[j],
marker:{
fillColor: 'green',
states: {
hover: {
fillColor: 'green',
lineColor: 'green'
}
}
}
});
}
}
}
});
";
}//end for
I'm calling the data like this
var teamweighinLMgameAction = window.localStorage.getItem("teamweighinLMgameAction");
AGWeigh = JSON.parse(teamweighinLMgameAction);
var toolTip = AGWeigh.toolTip;
alert(toolTip);//On alert it comes fine
if(data_avail=='yes') { //check if data available
var danger = myDangerLine,
deltaX = danger[1][0] - danger[0][0],
deltaY = danger[1][1] - danger[0][1],
delta = deltaY / deltaX;
alert("In: "+toolTip);//the data also alerts fine here
toolTip; //This is the place where I need the loop output but it nothing comes up
}
Ok this sounds like "Loop Code" being result of an AJAX call has passed js code "var chart = $('#team_containerWF').highcharts();..."!! However, this will never get executed by the main page. An AJAX result being passed should ideally be JSON/XML and then only contain name value pairs of data. Such that your main code being viewed would:
validate those name value pairs
execute its own code to render the graph based on those name value pairs
Therefore, my recommendation is try to structure it that firstly Main page handles the logic for display in Javascript, and AJAX pages in PHP handle the logic for pulling data and not display.
Also you could provide us with a bit more detail on the structure of your project. Label your code e.g. index.php getChartPlayingDates.php?