geojson data loaded into leaflet map and php/html page - javascript

I currently have an html page divided into 2 columns - the right side is a Leaflet map with markers and the left hand side describes a bit more about the markers. I load the Leaflet map using geoJson data on the right side and the map and markers display fine. Now I want to take the same geoJson data and use it to fill in the left side of the php page. This way, only one file needs to be updated as we add sites.
Here is a sample of my geoJson data:
var historicalMarkers = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-77.423603, 38.865608 ]
},
"properties": {
"id": 1,
"siteName": "House14"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [ -77.416770, 38.923650]
},
"properties": {
"id": 2,
"siteName": "Meeting House"
}
}..........
On the main php page, I simply include my geoJson file (places.js) and my geoJson/Leaflet code (map-geoJson.js).
On this main php page, I would like descriptions of each of the markers. In map-geoJson.js I am passing the data back to php via ajax like this:
// get stuff ready for php
var historicalData = [];
for (var i = 0; i < historicalMarkers.features.length; i++) {
var currentFeature = historicalMarkers.features[i];
var id = currentFeature.properties.id;
var siteName = currentFeature.properties.siteName;
console.log(id, siteName);
historicalData.push({ id: id, siteName : siteName });
}
var historicalJson = JSON.stringify(historicalData);
$.ajax({
url: location.pathname, //current page
type: 'POST',
data: historicalJson
});
The data is displayed on the console and is correct. On my php page, I want to grab the data and put it into several different divs on the page:
$phpArray = json_decode($_POST['historicalJson']);
var_dump ($phpArray); // NULL is displayed
foreach ( $phpArray as $value )
{ ?>
<div class="id">
<h4><?php echo $value['id']; ?></h4>
</div>
<div class="siteName">
<h4><?php echo $value['siteName']; ?></h4>
</div>
......
<?php } ?>
But nothing is displayed. I've also tried echo'ing
echo $value[0]->id;
echo $value['id']
Somehow I am not grabbing the data correctly in the php page and echo'ing it into the div.
Can anyone lend a suggestion? I'm sure it is something small I am missing, but I've tried many, many ways to grab the data in php.
Thanks

json_decode() returns an object (stdClass) per default. If you want to use the data as an array, you need to set the second parameter of the function to true :
$phpArray = json_decode($_POST['historicalJson'], true);
See json_decode documentation

Related

Unable to retrieve JSON value from PHP and Javascript

I have the following JSON below that I want to parse and get the value of the TotalRows. However, in my PHP and JavaScript it returns an error or undefined when I try to access it and I am not sure why.
For JavaScript:
var data = <?php echo json_encode($customers); ?>;
console.log(data.TotalRows)
I even placed console.log(data) and it gave me the JSON I posted and then I did console.log(data[0].TotalRows) and it give me undefined.
My code for PHP is, where $customers returns the JSON below:
$customers = $customerDB->findCustomer(5, 1);
$arr = json_decode($customers, true);
echo $arr["TotalRows"];
[
{
"TotalRows":91,
"Rows":[
{
"CompanyName":"Ana Trujillo Emparedados y helados",
"ContactName":"Ana Trujillo",
"ContactTitle":"Owner",
"City":"M\u00e9xico D.F.",
"Country":"Mexico"
},
{
"CompanyName":"Antonio Moreno Taquer\u00eda",
"ContactName":"Antonio Moreno",
"ContactTitle":"Owner",
"City":"M\u00e9xico D.F.",
"Country":"Mexico"
},
{
"CompanyName":"Around the Horn",
"ContactName":"Thomas Hardy",
"ContactTitle":"Sales Representative",
"City":"London",
"Country":"UK"
},
{
"CompanyName":"Berglunds snabbk\u00f6p",
"ContactName":"Christina Berglund",
"ContactTitle":"Order Administrator",
"City":"Lule\u00e5",
"Country":"Sweden"
},
{
"CompanyName":"Blauer See Delikatessen",
"ContactName":"Hanna Moos",
"ContactTitle":"Sales Representative",
"City":"Mannheim",
"Country":"Germany"
}
]
}
]
Its an array of object, so you would get TotalRows by
console.log(data[0].TotalRows);
Actually, I figured it out. The following worked:
var data = <?php echo json_encode($customers); ?>;
var data = JSON.parse(data);
console.log(data[0].TotalRows);

How to pass custom Wordpress fields into mapbox-gl js to create markers on map?

I'm trying to create a map plotting different points using Mapbox and Wordpress. In Wordpress I created a custom post type with the coordinates stored in custom meta fields. The fields are all setup, but I am having trouble passing them into the javascript in my php template.
I tried using a loop, but can't use it as the coordinates need to be stored inside the javascript. Seems like storing the custom meta fields in a geoJSON is the only solution.
Here is what the Mapbox code should look like, the coordinates and title should come from the posts and custom fields though:
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/coptmarketing/cjvi7hc4602dk1cpgqul6mz0b',
center: [-76.615573, 39.285685],
zoom: 16 // starting zoom
});
var geojson = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"title": "Shake Shack"
},
"geometry": {
"type": "Point",
"coordinates": [-76.609844, 39.286894]
}
},
{
"type": "Feature",
"properties": {
"title": "Starbucks"
},
"geometry": {
"type": "Point",
"coordinates": [-76.619071, 39.286649]
}
}
]
};
My PHP looks like this to get the custom fields and transform it into JSON:
<?php $args = array(
'post_type' => 'places',
'post_status' => 'publish',
'nopaging' => true
);
$query = new WP_Query( $args ); // $query is the WP_Query Object
$posts = $query->get_posts(); // $posts contains the post objects
$output = array();
foreach( $posts as $post ) { // Pluck the id and title attributes
$output[] = array(
'id' => $post->ID,
'title' => $post->post_title,
'address' => get_post_meta($post->ID,'ci_cpt_adresse', true),
'longitude' => get_post_meta($post->ID, 'ci_cpt_adressex', true),
'altitude' => get_post_meta($post->ID, 'ci_cpt_adressey', true)
);
}
$data = json_encode(['placelist' => $output]);
?>
I then tried processing the data via this script. However, it doesn't return anything:
<script>
var placeJson = data;
var stores = {
"type:" "FeatureCollection",
"features:" [],
};
for (i = 0; i < placeJson.placelist.length; i++) {
geojson.features.push({
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [placeJson.placelist.[i].altitude, placeJson.placeList[i].longitude]
},
"properties": {
"title": placeJson.placelist.[i].title
}
},);
}
</script>
<script>
stores.features.forEach(function(store, i){
store.properties.id = i;
});
</script>
I already found a possible solution here, but don't understand how to get it into geoJSON: How to pass custom fields into mapbox-gl js to create points on map?
you can do so via wp_localize_script (please note below code is an example and needs to be altered to work in your case)
wp_enqueue_script( 'my_mapbox', get_template_directory_uri() . '/js/mabox.js' );
$dataToBePassed = array(
'home' => get_stylesheet_directory_uri(),
'pleaseWaitLabel' => __( 'Please wait...', 'default' )
);
wp_localize_script( 'my_mapbox', 'php_vars', $datatoBePassed );
and then in your script call to the localized object
https://code.tutsplus.com/tutorials/how-to-pass-php-data-and-strings-to-javascript-in-wordpress--wp-34699
Basically, there are three solutions here. Which one is relevant for you highly depends on your use case ofcourse!
Run your custom post query in the function that you use to enqueue the script in and localise a variable in wp_localize_script with the data from the Query (Jasper B his solution above :) )
Inline the php with the script. PHP code is on same page as inlined script (hacky but quick for testing). Something like this (correct the closing php):
var data = <?php $data ?"> // TODO Correct this pls! I can't write it here. As long this is encoded, it
should provide you with an array of data, just console.log it to see
if it's correct.
You can create an endpoint with Ajax or with Wordpress REST, and in your JS file query the data and display it. Here is some more info on how to set up an Ajax Get request

modifying a json file of world country polygons to customise colours

I am using a JavaScript package which displays global flows between lat/long coordinates from a CSV file.
The JS package calls a JSON file which provides country polygon shape data. I would like some of the countries to appear in different colours. Being unfamiliar with JSON, I am struggling to modify the code to achieve this customization. I have looked through various tutorials but still getting errors or no effect at all.
Here is example JSON code for Afghanistan:
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"name": "Afghanistan"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[61.210817, 35.650072],
[62.230651, 35.270664],
[62.984662, 35.404041],
[63.193538, 35.857166],
[63.982896, 36.007957],
[64.546479, 36.312073],
[64.746105, 37.111818],
[65.588948, 37.305217],
[65.745631, 37.661164],
[66.217385, 37.39379],
[66.518607, 37.362784],
[67.075782, 37.356144],
[67.83, 37.144994],
[68.135562, 37.023115],
[68.859446, 37.344336],
[69.196273, 37.151144],
[69.518785, 37.608997],
[70.116578, 37.588223],
[70.270574, 37.735165],
[70.376304, 38.138396],
[70.806821, 38.486282],
[71.348131, 38.258905],
[71.239404, 37.953265],
[71.541918, 37.905774],
[71.448693, 37.065645],
[71.844638, 36.738171],
[72.193041, 36.948288],
[72.63689, 37.047558],
[73.260056, 37.495257],
[73.948696, 37.421566],
[74.980002, 37.41999],
[75.158028, 37.133031],
[74.575893, 37.020841],
[74.067552, 36.836176],
[72.920025, 36.720007],
[71.846292, 36.509942],
[71.262348, 36.074388],
[71.498768, 35.650563],
[71.613076, 35.153203],
[71.115019, 34.733126],
[71.156773, 34.348911],
[70.881803, 33.988856],
[69.930543, 34.02012],
[70.323594, 33.358533],
[69.687147, 33.105499],
[69.262522, 32.501944],
[69.317764, 31.901412],
[68.926677, 31.620189],
[68.556932, 31.71331],
[67.792689, 31.58293],
[67.683394, 31.303154],
[66.938891, 31.304911],
[66.381458, 30.738899],
[66.346473, 29.887943],
[65.046862, 29.472181],
[64.350419, 29.560031],
[64.148002, 29.340819],
[63.550261, 29.468331],
[62.549857, 29.318572],
[60.874248, 29.829239],
[61.781222, 30.73585],
[61.699314, 31.379506],
[60.941945, 31.548075],
[60.863655, 32.18292],
[60.536078, 32.981269],
[60.9637, 33.528832],
[60.52843, 33.676446],
[60.803193, 34.404102],
[61.210817, 35.650072]
]
]
},
"id": "AFG",
"color": "#000"
}]
}
I assume you are playing with D3.
Make sure you have loaded topojson then use
d3.json ( url , function (error, world) {
var countries = topojson.feature(world, world.objects.countries).features;
countries.forEach ( function (country,index) {
if ( country.properties.name =="Afghanistan" ) country.properties.color ='#color';
});
});
if you don't use D3 - ignore my reply ;)

How to get properties from feature without event listener? (event.feature)

how to get the "feature" data from a layer (loaded with geoJSON) without event listener?
thats the usual way, which works fine:
layer1.addListener('mouseover', function (event) {
console.log( event.feature.getProperty('description') );
}
but now i want to get the value from data object "layer1".
i tried already this:
layer1.getProperty('description')
layer1.feature.getProperty('description')
The way how i load the geoJSON
var layer1 = new google.maps.Data();
layer1 = loadGeoJson('https://googledrive.com/host/MYFILE')
The content of json
Here a short question btw: if i have more features (e.g polygons) in my json, can i get this values to manipulate (e.g. toggle visibility) it?
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
12.3456789,
01.2345678,
0
]
},
"properties": {
"name": "Test Polygon",
"description": "My Test Description"
}
}
]
}
To get all the features of a google.maps.Data Layer, use:
forEach(callback:function(Data.Feature))
Return Value: None
Repeatedly invokes the given function, passing a feature in the collection to the function on each invocation. The order of iteration through the features is undefined.
or to get a single feature (if you know the Id):
getFeatureById(id:number|string)
Return Value: Data.Feature|undefined
Returns the feature with the given ID, if it exists in the collection. Otherwise returns undefined.
Note that the IDs 1234 and '1234' are equivalent. Either can be used to look up the same feature.

"Loading Data" Stuck on AMChart

Hello,
I am using the AMCharts framework to make charts from data in MySQL database. I get stuck with "Loading Data" instead of an actual chart. (http://gyazo.com/b72693484ab39e2635c0a0ab21c889a5)
And no, it's not actually loading the data. I went to launch and came back an hour later and it's yet to be loaded. When I used the data the AMCharts website provided, it worked just fine, but with my own data, no such luck.
Also, I have checked this link and it isn't answering my question. So this question shouldn't be a duplicate.
The Data :
For my data, I am using a section of Starbucks stock close prices for 100 dates in 2007. It's basically test data before I start the real part of the project. Just to get things rolling. Originally I started with 2100 rows, but when I first got the "Loading Data" message, I cut down my data to a simple 100 rows. But still, no such luck.
If you'd like to get the data I used, the way I got it, here is the R code I used.
require('quantmod')
getSymbols("SBUX")
starbucks <- data.frame(SBUX)
starbucks[,7] <- row.names(starbucks)
starbucks <- data.frame(starbucks[,c(7,6)])
row.names(starbucks) <- NULL
colnames(starbucks) <- c("Dates","Values")
starbucks <- data.frame(starbucks[1:100,])
write.table(starbucks, file="path\\to\\file\\starbucks.csv", sep=",")
Upload:
I created a new database called "charts" and under it made a table named "starbucks". There were two columns under starbucks named "Dates" (set as Date) and "Values" (set as float) each given a length of 10.
I then went to import and uploaded the CSV to this table and all imported well.
PHP
This is the code I used for the PHP side of things.
<?php
// Connect to MySQL
$link = mysql_connect( 'localhost', 'root', '' );
if ( !$link ) {
die( 'Could not connect: ' . mysql_error() );
}
// Select the data base
$db = mysql_select_db( 'charts', $link );
if ( !$db ) {
die ( 'Error selecting database \'test\' : ' . mysql_error() );
}
// Fetch the data
$query = "
SELECT *
FROM starbucks";
$result = mysql_query( $query );
// All good?
if ( !$result ) {
// Nope
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die( $message );
}
// Print out rows
$data = array();
while ( $row = mysql_fetch_assoc( $result ) ) {
$data[] = $row;
}
echo json_encode( $data );
// Close the connection
mysql_close($link);
?>
Javascript
Then there is the Javascript side of things.
var chart = AmCharts.makeChart( "chartdiv", {
"type": "serial",
"dataLoader": {
"url": "../scripts/data.php"
},
"pathToImages": "http://www.amcharts.com/lib/images/",
"categoryField": "category",
"dataDateFormat": "YYYY-MM-DD",
"startDuration": 1,
"rotate": false,
"animationDuration": 0,
"minSelectedTime": 100,
"categoryAxis": {
"parseDates": true
},
"graphs": [ {
"valueField": "value1",
"bullet": "square",
"bulletBorderColor": "#FFFFFF",
"bulletBorderThickness": 2,
"lineThickness ": 2,
"lineAlpha": 0.5
} ]
} );
HTML
Theres is of course, HTML.
<div id="chartdiv" style="width:100%; height:400px;"></div>
So back to the problem
After copy/pasting all that code, back to the actual question of this post. Why am I getting "Loading Data" instead of an actual chart?
IF there is anything else needed, let me know. I've done my best to not be vague in this question.
I'm having a similar issue. If I save the json output, remove the preceding square braces, and use this as my input, it works:
JSON that doesn't work:
[
[],
{"Key1":"Val1","Key2":"Val1"},
{"Key1":"Val2","Key2":"Val2"},
...
]
JSON that works:
[
{"Key1":"Val1","Key2":"Val1"},
{"Key1":"Val2","Key2":"Val2"},
...
]
Modify your AmChart.makeChart bit to test json:
"dataLoader": {
"url": "test.json",
"format": "json"
},
..but I don't know how to remove the preceding braces in my PHP code.. Hopefully this will get you a step closer to resolution...
I tried everything, in the end I used AJAX to retrive content and insert it in dataprovider.
jQuery.ajax({
url: "api/chartdata,
type: "GET",
contentType: 'application/json; charset=utf-8',
success: function (resultData) {
console.log(resultData);
lineChart.dataProvider = JSON.parse(resultData);
lineChart.validateData();
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
finally I have solution
i don't know why amchart output "data loading..." but don't output real problem
if someone don't use browser(me is chrome) ctrl+shift+J to look up error message,
he would never found why always "data loading..."
two problem that cause "data loading" situation is confirmed
1.you open local html and browser(or amchart) block javascript to read local file
2.your file doesn't exist at all
you need something like apache to simulate amchart work at real enviroment
put html,json,lib to httpdoc

Categories