If php string is in geojson array - javascript

I am trying to make a selection of country names via php, then do a check against my geojson to see if the country name I got from php matches any names in my json and if so, read the coordinates of it.
So basically I have ALL the countries in the geojson but only those that are found to match with my php variable get drawn with polygons.
The example is using leaflet, what if those countries where coloured only if my php variables with the country names matches?
I have a php string which i get like this:
$myCountry = get_field("country");
echo $myCountry;
String name result is Australia
This is the var_dump of get_field()
array(3) {
["country_name"]=>
string(9) "Australia"
["city_name"]=>
bool(false)
["state_name"]=>
bool(false)
}
I have a geojson like this
"type": "Feature",
"properties": {
"sovereignt": "Australia"
},
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[-77.53466, 23.75975],
[-77.78, 23.71],
[-78.03405, 24.28615],
[-78.40848, 24.57564],
[-78.19087, 25.2103],
[-77.89, 25.17],
[-77.54, 24.34],
[-77.53466, 23.75975]
]
],
[
[
[-77.82, 26.58],
[-78.91, 26.42],
[-78.98, 26.79],
[-78.51, 26.87],
[-77.85, 26.84],
[-77.82, 26.58]
]
],
[
[
[-77, 26.59],
[-77.17255, 25.87918],
[-77.35641, 26.00735],
[-77.34, 26.53],
[-77.78802, 26.92516],
[-77.79, 27.04],
[-77, 26.59]
]
]
]
}
},

Related

Converting a list of JSON polygon coordinates to Long/Lat arrays in GeoJSON format

I am fetching data from a REST API which results in a list of datasets. Some of these datasets contain coordinates that I want to project on a map. In order to project the coordinates, I need to convert the JSON output to GeoJSON. While the conversion goes well for most parts of the data. I struggle with a long array containing x and y coordinates. It is 4+ points combined into polygons (5th endpoint = begin point is missing).
How can I convert this one array with 4+ XY coordinates to the right format while also adding the last one that should match the first point?
I thought about slicing the array into new ones for each point but this would result in too much work for polygons with over 20 points.
Example of the JSON:
"footprint": {
"epsgId": 4326,
"data": [
[
5.785569964298996,
50.94215924789526,
5.934953425435474,
50.94154873163077,
5.9341556116101595,
50.87413533708443,
5.784989651500041,
50.87474468292546
]
],
},
This is how it should look like after conversion into GeoJSON. I wrote this down myself, but I need a JavaScript code to do this automatically while looping through the results.
{
"type": "Feature",
"properties": {
"name": "name"
"id" : "id"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[5.785569964298996, 50.94215924789526],
[5.934953425435474, 50.94154873163077],
[5.9341556116101595, 50.87413533708443],
[5.784989651500041, 50.87474468292546],
[5.785569964298996, 50.94215924789526]
]
]
}
}
i think this function will do the work for you.
d = {"footprint": {
"epsgId": 4326,
"data": [
[
5.785569964298996,
50.94215924789526,
5.934953425435474,
50.94154873163077,
5.9341556116101595,
50.87413533708443,
5.784989651500041,
50.87474468292546
]
],
}
}
console.log(d)
function convert(points)
{
geojson = {
"geometry": {
"type": "Polygon",
"coordinates": [
]
}
}
var coordinates = new Array();
for (var i = 0; i < points.length; i+=2) {
coordinates.push([points[i],points[i+1]])
}
//closing the polygon
coordinates.push([points[0],points[1]])
// points need to be in zero index of coordinates array
geojson.geometry.coordinates = new Array(coordinates);
return geojson;
}
console.log(convert(d["footprint"]["data"][0]))

HereMaps GeoJSON Polygon click read properties

my question is as follows.
What I have
I have a GeoJSON feature collection with Polygons and custom properties
GeoJSON is loaded into the Here maps
What I want
I want to detect a polygon click and read the custom property value
Example GeoJSON
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"customProp": "heyImACustomProperty"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
16.45477294921875,
43.51619059561274
],
[
16.450481414794922,
43.50772499687011
],
[
16.470909118652344,
43.5019975949657
],
[
16.481552124023438,
43.51021500212034
],
[
16.475543975830078,
43.518306809754804
],
[
16.45477294921875,
43.51619059561274
]
]
]
}
}]
}
Docs on GeoJSON manipulation are not the greatest.
Thanks in advance.
Here is the example code to get the property value of the GeoJSON Polygon on click.
reader = new H.data.geojson.Reader('/path/to/geojson/file.json');
reader.parse();
map.addLayer(reader.getLayer());
reader.getLayer().getProvider().addEventListener("tap", function(e) {
if(e.target instanceof H.map.Polygon) {
console.log('Custom property value: ', e.target.getData().properties.customProp);
}
});
GeoJSON documentation can be found here:
https://developer.here.com/documentation/maps/topics_api/h-data-geojson-reader.html

GeoJSON formats for Leaflet -- certain GeoJSON not displaying, while others are

I am modifying an example Leaflet script for my custom purposes.
The original had an associated GeoJSON file with the following format (this is just an excerpt):
{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"OBJECTID":1,"NAME":"Alpha Terrace","TYPE":"CHD"},"geometry":{"type":"Polygon","coordinates":[[[-79.9222757299766,40.4687885729535],[-79.922601544034,40.4688999202888],[-79.9227665690647,40.4689585131248],[-79.9231802736014,40.4691056186529],[-79.9228362255,40.4696697431611],[-79.9224234733987,40.4695244210813],[-79.9222570954656,40.4694656801973],[-79.9222259241735,40.4695164633706],[-79.9219035919843,40.4694017028541],[-79.9222757299766,40.4687885729535]]]}},{"type":"Feature","properties":{"OBJECTID":2,"NAME":"Manchester","TYPE":"CHD"},"geometry":{"type":"Polygon","coordinates":[[[-80.0271753891687,40.4506598454243],[-80.0271940086199,40.4507189442263],[-80.0272105946986,40.4507710471721],[-80.0272579314302,40.4509221686618],[-80.0273032612578,40.4510537660432],[-80.0273193174278,40.451103476753],[-80.0273338296879,40.451147381945],[-80.0273478698275,40.451190610864],[-80.0273633786279,40.4512374152857],[-80.0273793914473,40.4512858394759],[-80.0273919427229,40.4513248923929],[-80.0274084625005,40.4513750227769],[-80.0274174596111,40.451401961247],
I made my own GeoJSON with this format (again, just an excerpt):
{
"type": "FeatureCollection",
"name": "testmap1",
"features": [
{ "type": "Feature", "properties": { "land_val": 16290.0, "imprv_val": 0.0, "land_acres": 0.31, "land_sqft": 13503.6, "situs_stre": null, "situs_st_1": "LAKE BREEZE", "situs_st_2": "DR", "situs_city": "BROWNWOOD", "Deed_Date": "2014\/10\/14", "Mkt_Land_S": "FBINT" }, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ 2695178.255351334810257, 10617843.194646343588829 ], [ 2695245.314272344112396, 10618016.961359173059464 ], [ 2695316.911570087075233, 10617988.845273673534393 ], [ 2695251.204024344682693, 10617828.19828525185585 ], [ 2695196.89442166686058, 10617839.362961083650589 ], [ 2695178.255351334810257, 10617843.194646343588829 ] ] ] ] } },
I'm aware that these are in different locations -- I edited the coordinates of the map so that they display the area covered by the new GeoJSON.
When the map displays with my GeoJSON nothing shows up. But when I use the original GeoJSON (and move the window back to that area), it overlays polygons onto the OSM map.
Does anyone know why this might be? Is there a hyper-specific GeoJSON format needed for Leaflet?
Your coordinates are completely off (e.g [ 2695178.255351334810257, 10617843.194646343588829]).
First value (i.e. longitude) should be 0 to 360
Second value (i.e. latitude) should be -90 to 90

pg-promise wrong insertion of multipolygons into postgis database

So I am using pg-promise to insert multiple geojson MultiPolygons into a postgis database. The insertion into the database work fine, but for some of the row in the database I get a strange behaviour, that is the cell is filled with two lines. The first line some load message and the second line is the actual geom object which more strangely is converted right from geojson to postgis geom.
function createBorder(pathToJSON, table) {
fs.readFile(pathToJSON,
{encoding: 'UTF-8'},
(err, data) => {
let geoJSON = JSON.parse(data);
geoJSON.features.forEach(f => {
f.geometry.crs = {
type: 'name',
properties: {
name: 'EPSG:4326'
}
}
db.none('INSERT INTO nyc_borders(geom)\
VALUES (ST_GeomFromGeoJSON(${geoJSON}))', {
geoJSON: f.geometry
})
.then((d) => {
console.log(f.geometry);
})
.catch(error => {
console.log("ERROR: ", error);
})
});
});
}
createBorder('./data/community_districts.geojson');
I shortend the geoJSON output, it is basically the community district borders from nyc downloaded from the opendata portal
Geojson:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"shape_leng": "51549.5578986",
"boro_cd": "311",
"shape_area": "103177785.347"
},
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[
-73.97348373564797,
40.61137106069874
],
[
-73.97303089190211,
40.6090051063008
],
[
-73.97299433938896,
40.60881414180224
]
]
]
]
}
},
{
"type": "Feature",
"properties": {
"shape_leng": "65821.875617",
"boro_cd": "313",
"shape_area": "88195686.2688"
},
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[
-73.96720294103956,
40.573326317397424
],
[
-73.96738975478877,
40.573258999904446
],
[
-73.9674356779313,
40.57320896967127
],
[
-73.96736390080571,
40.57304456895217
],
[
-73.98372152615246,
40.59582107821707
]
]
]
]
}
}
]
}
Some pictures from my database:
database table with rows that have two lines inside one cell
one cell expanded to see the actual tow lines better
So I am really stuck because I do not have an idea how to start debuging, singe the insertion does work some how and also the conversion of the geojson object looks fine. I actually can not figure out who is causing this wrong behaviour.
You can have full control over how pg-promise formats data, by using Custom Type Formatting.
For example, if you have an array[][2] (points as shown), you can convert them like this:
const toGeometry = g => ({ /* g = array[][2] (points) */
rawType: true,
toPostgres: a => {
const points = a.map(p => pgp.as.format('$1 $2', p));
return 'ST_GeomFromText(\'LINESTRING(' + points.join() + ')\')';
}
});
And then you can pass in toGeometry(f.geometry) to apply your custom formatting.
See also: ST_GeomFromText.
I found the solution for my problem the two lines displayed in the pictures that confused me where only information added by datagrip to tell me that the huge polygons where not loaded fully.
I had a look into the same rows with psql:
SELECT ST_ASGEOJSON(geom) FROM <tablename> WHERE id=<myid>
and there the second line would not show up.
Then I realised it is just additional information.

How to parse JSON data from nested array in PHP

I am struggling to retrieve some values from a JSON file formatted like this:
{
"#context": [
"https://raw.githubusercontent.com/geojson/geojson-ld/master/contexts/geojson-base.jsonld",
{
"wx": "https://api.weather.gov/ontology#",
"#vocab": "https://api.weather.gov/ontology#"
}
],
"type": "FeatureCollection",
"features": [
{
"id": "https://api.weather.gov/alerts/NWS-IDP-PROD-2485131-2320093",
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-95.45,
32.36
],
[
-96.07,
32.36
],
[
-96.08,
32.76
],
[
-95.92,
32.82
],
[
-95.85,
32.77
],
[
-95.77,
32.77
],
[
-95.76,
32.75
],
[
-95.71,
32.75
],
[
-95.66,
32.71
],
[
-95.64,
32.72
],
[
-95.59,
32.68
],
[
-95.6,
32.48
],
[
-95.47,
32.37
],
[
-95.45,
32.36
]
]
]
},
"properties": {
"#id": "https://api.weather.gov/alerts/NWS-IDP-PROD-2485131-2320093",
"#type": "wx:Alert",
"id": "NWS-IDP-PROD-2485131-2320093",
"areaDesc": "Van Zandt",
"geocode": {
"UGC": [
"TXC467"
],
"SAME": [
"048467"
]
},
"references": [],
"sent": "2017-08-13T00:03:41+00:00",
"effective": "2017-08-13T00:03:41+00:00",
"onset": "2017-08-13T00:03:00+00:00",
"expires": "2017-08-13T01:00:00+00:00",
"ends": "2017-08-13T01:00:00+00:00",
"status": "Actual",
"messageType": "Alert",
"category": "Met",
"severity": "Severe",
"certainty": "Observed",
"urgency": "Immediate",
"event": "Severe Thunderstorm Warning",
"sender": "NWS Fort Worth TX",
"headline": "Severe Thunderstorm Warning issued August 12 at 7:03PM CDT expiring August 12 at 8:00PM CDT by NWS Fort Worth TX",
"description": "The National Weather Service in Fort Worth has issued a\n\n* Severe Thunderstorm Warning for...\nVan Zandt County in north central Texas...\n\n* Until 800 PM CDT.\n\n* At 703 PM CDT, a severe thunderstorm was located near Wills Point,\nmoving east at 25 mph.\n\nHAZARD...65 mph wind gusts and quarter size hail.\n\nSOURCE...Radar indicated.\n\nIMPACT...Hail damage to vehicles is expected. Expect wind damage\nto roofs, siding, and trees.\n\n* This severe thunderstorm will be near,\nCanton around 710 PM CDT.\nEdgewood around 715 PM CDT.\nFruitvale around 725 PM CDT.\nGrand Saline around 735 PM CDT.\nVan around 750 PM CDT.\n\nThis includes Interstate 20 between mile markers 513 and 542.",
"instruction": "For your protection get inside a sturdy structure and stay away from\nwindows.\n\nContinuous cloud to ground lightning is occurring with this storm.\nMove indoors immediately. Lightning can kill.\n\nHeavy rainfall is occurring with this storm, and may lead to flash\nflooding. Do not drive your vehicle through flooded roadways.",
"response": "Shelter",
"parameters": {
"eventMotionDescription": [
"2017-08-13T00:03:00.000-05:00...storm...277DEG...23KT...32.62,-95.97"
],
"hailSize": [
"1.00"
],
"windGust": [
65
],
"tornadoDetection": [
"POSSIBLE"
],
"VTEC": [
"/O.NEW.KFWD.SV.W.0313.170813T0003Z-170813T0100Z/"
],
"EAS-ORG": [
"WXR"
],
"PIL": [
"FWDSVRFWD"
],
"BLOCKCHANNEL": [
"CMAS",
"EAS",
"NWEM"
],
"eventEndingTime": [
"2017-08-13T01:00:00Z"
]
}
}
},
I am trying to get the values from the keys under the "properties" key. What I am struggling with is does the array start with "properties" nested under #context or under "features"? I am not familiar with JSON data that uses # keys.
There are more values I need. But for starters, I am just using the event key nested under "features" -> "properties" where most of the keys for the values I need. I am not getting output from that.
<?php
$url = 'http://stream.dfwstormforce.com/json/nat_alerts.json'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$result = json_decode($data, true); // decode the JSON feed
foreach($results as $result) {
dump($result); //this will dump the array
foreach($results['features'] as $data) {
dump($data['event']);
}
}
?>
-Thanks
EDIT: Added suggestion to code for json_decode
As others have stated, you need to pass true as a second param to json_decode if you want to the result to be an associative array.
The hierarchy is features/properties/event so you can look through the features and pull what you want out of the properties of each feature.
<?php
$url = 'http://stream.dfwstormforce.com/json/nat_alerts.json'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$results = json_decode($data, true); // decode the JSON feed
foreach($results['features'] as $currFeature)
{
$currEvent = $currFeature['properties']['event'];
echo $currEvent."\n";
}
Use json_decode($data, true). The true tells json_decode to return nested associative arrays instead of a object.
As BarNakedCoder said:
json_decode($data, true)
but you also need to replace
dump($data['event']
with:
dump($data[0]['event'])

Categories

Resources