How to convert JSON to GeoJson JavaScript - javascript

I've got a JSON from a database but now I need to convert it into GeoJson to use it in my map
I found this solution but it shows an undefined array.
$.getJSON("./origin/neworigin.json", function(jsonData) {
var outGeoJson = {}
outGeoJson['properties'] = jsonData
outGeoJson['type']= "Feature"
outGeoJson['geometry']= {"type": "Point", "coordinates":
[jsonData['latitude'], jsonData['longitude']]}
console.log(outGeoJson)
});
This is an example from myJSON
[{"station":"BORJA","institution":"SENCICO","longitude":"-77.0064","latitude":"-12.0855"},
{"station":"SCARQ","institution":"SENCICO","longitude":"-71.5408","latitude":"-16.385"},
{"station":"SCAR2","institution":"SENCICO","longitude":"-71.5364","latitude":"-16.3934"},...
in browser

Check if the array is empty or not.
Try change the variable names.
OR
Provide more details.

You have two options to create a valid GeoJSON form JSON.
create GeoJSON.Point array and GeoJSON.FeatureCollection
create GeoJSON.MultiPoint object
Here are code snippets:
const jsonData = [{
"station": "BORJA",
"institution": "SENCICO",
"longitude": "-77.0064",
"latitude": "-12.0855"
},
{
"station": "SCARQ",
"institution": "SENCICO",
"longitude": "-71.5408",
"latitude": "-16.385"
},
{
"station": "SCAR2",
"institution": "SENCICO",
"longitude": "-71.5364",
"latitude": "-16.3934"
}
];
// to GeoJSON.Point array
const geoJSONPointArr = jsonData.map(row => {
return {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [row.longitude, row.latitude]
},
"properties": row
}
});
console.log(geoJSONPointArr);
// to GeoJSON.FeatureCollection
const pointArrFeatureCollection = {
"type": "FeatureCollection",
"features": geoJSONPointArr
}
console.log(pointArrFeatureCollection);
// to GeoJSON.MultiPoint
const geoJSONMultiPoint = {
"type": "Feature",
"geometry": {
"type": "MultiPoint",
"coordinates": jsonData.map(row => [row.longitude, row.latitude])
},
"properties": {
originalData: jsonData
}
}
console.log(geoJSONMultiPoint);
I would also recommend using the turf library, which is very convenient when working with the GeoJSON format.

Related

Leaflet not show EPSG:3857 coordinates

I am totally stuck with my WGS 84 / EPSG:3857 coordinates and display them on Leaflet.
I have Geojson with coordinates.
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
"6690861",
"682187"
]
},
"properties": {
"id": "908",
"message": "105",
"date": "",
"place": "",
"shape": ""
}
}
Now i want it display on Leaflet. But nothing show up. I search already 5 hours and find something about Proj4. Also no errors showing up.
My script code:
var map = L.map('map').setView([52.2129919, 5.2793703], 8);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution: 'Map data © OpenStreetMap'}).addTo(map);
// GeoJSON layer (UTM15)
proj4.defs('EPSG:3857');
async function addGeoJson() {
const response = await fetch("geojs.php");
const data = await response.json();
L.geoJson(data).addTo(map);
var layerGroup = L.geoJSON(data, {
onEachFeature: function (feature, layer) {
layer.bindPopup('<h1>'+feature.properties.message+'</h1><p>Datum: '+feature.properties.date+'</p>');
}
}).addTo(map);
}
addGeoJson();
It's for my the first time i work with this coordinates. With lat/long coordinates was don't have problems. And just started with javascript.
Kind regards,
I might be a bit late, but following the documentation of Proj4, I would say that you need to add the crs to your geojson, like so :
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
"6690861",
"682187"
]
},
"properties": {
"id": "908",
"message": "105",
"date": "",
"place": "",
"shape": ""
},
"crs": {
"type": "name",
"properties": {
"name": "urn:ogc:def:crs:EPSG::3857"
}
}
}
Also, I think it's
L.Proj.geoJson(data).addTo(map);
instead of
L.geoJson(data).addTo(map);
I tried L.geoJson on my code and it didn't show anything contrary to L.Proj.geoJson so it might be your problem here.

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

I've created a map using mapbox and plotted multiple custom points that you can interact with. I am also using Wordpress and want to use advanced custom fields to create each point so they can easily be managed from a non-technical person. The fields are all setup, but I am having trouble passing them into the javascript in my php template.
I've tried using a loop but I can't use the loop inside javascript. Here is my Mapbox code that I am using to plot the points and want to use advanced custom fields with:
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",
"id": "shake-shack"
},
"geometry": {
"type": "Point",
"coordinates": [-76.609844, 39.286894]
}
},
{
"type": "Feature",
"properties": {
"title": "Starbucks",
"id": "starbucks"
},
"geometry": {
"type": "Point",
"coordinates": [-76.619071, 39.286649]
}
}
]
};
I've stored the data in a JSON array:
[{"title":"Shake Shack","slug":"shake-shack","latitude":"-76.609844","longitude":"39.286894"},{"title":"Starbucks","slug":"starbucks","latitude":"-76.619071","longitude":"39.286649"}]
How do I insert this into the geoJSON?
Figured it out:
First I created a plugin that stored the custom post data in a JSON array and stored it on the server. This also updated every time I updated, saved or deleted a post. Here is the example JSON:
data = {"placeList": [{"title":"Shake Shack","slug":"shake-shack","latitude":"-76.609844","longitude":"39.286894"},{"title":"Starbucks","slug":"starbucks","latitude":"-76.619071","longitude":"39.286649"}]}
Then in the php file, I called the .json file and in my javascript, inserted the array into the GeoJSON:
var placeJson = data;
var geojson = {
type: "FeatureCollection",
features: [],
};
for (i = 0; i < placeJson.placeList.length; i++) {
geojson.features.push({
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [placeJson.placeList[i].latitude, placeJson.placeList[i].longitude]
},
"properties": {
"id": placeJson.placeList[i].slug,
"title": placeJson.placeList[i].title
}
});
}

How to make MarkerClusterGroup cluster polygons

I am trying to show clusters using markerclustergroups with Polygons. Right now the polygons are shown but the clusters aren't. I have been trying to use center of mass for the polygons because it seems like markerclustergroup doesn't like polygons but that doesn't really work since the animation of markerclustergroup will be set on the centroids and not the actual polygon.
My polygons all vary in amount of coordinates. Some have +10 sets others have 3.
How would I use markerclustergroup for polygons?
Below my code can be seen:
// Create variable to hold map element, give initial settings to map
var map = L.map('map', {
center: [23.70489, 43.90137],
zoom: 5
});
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
}).addTo(map);
var ojStyle = {
"color": "#ff7800",
"weight": 5,
"opacity": 0.65
};
// Hardcoded polygons as GeoJSON
var polygons = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[37.99896240234376, 21.55017532555692],
[39.39422607421876, 21.476073444092435],
[38.88336181640626, 22.56582956966297],
[38.023681640625, 22.611475436593366],
[37.43591308593751, 21.99908185836153],
[37.28485107421876, 21.624239377938288],
[37.28485107421876, 21.624239377938288],
[37.99896240234376, 21.55017532555692]
]
]
}
}, {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[38.50708007812501, 21.453068633086783],
[39.20745849609376, 21.37124437061832],
[39.10858154296876, 20.876776727727016],
[38.80920410156251, 20.912700155617568],
[38.49884033203126, 20.94604992010052],
[38.50708007812501, 21.453068633086783]
]
]
}
}, {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[50.57830810546875, 25.980268007469803],
[50.77606201171876, 25.956809920555312],
[50.780181884765625, 25.69970044378398],
[50.56457519531251, 25.822144306879686],
[50.56182861328126, 25.945696562830516],
[50.57830810546875, 25.980268007469803]
]
]
}
}, {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[54.37408447265626, 24.51963836811676],
[54.29443359375001, 24.40963901896311],
[54.25872802734375, 24.449649897759667],
[54.32739257812501, 24.539627918861232],
[54.37133789062501, 24.559614286039903],
[54.37408447265626, 24.51963836811676]
]
]
}
}, {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[54.40155029296876, 24.463400705082282],
[54.41940307617188, 24.489648077028683],
[54.45785522460938, 24.462150693715266],
[54.43450927734376, 24.43839812102505],
[54.40155029296876, 24.463400705082282]
]
]
}
}]
}
var polygonArray = []
for (i = 0; i < polygons.features.length; i++) {
polygonArray.push(polygons.features[i]);
}
var markers = L.markerClusterGroup().addTo(map);
var geoJsonLayer = L.geoJson(polygonArray);
markers.addLayer(geoJsonLayer);
map.fitBounds(markers.getBounds());
http://js.do/code/165930 - Shows how clustering doesn't work for the polygons
I am looking for a solution like this: http://jsfiddle.net/ve2huzxw/237/
You can do it very much like in this GIS post: Is it possible to cluster polygons in Leaflet?
// Compute a polygon "center", use your favourite algorithm (centroid, etc.)
L.Polygon.addInitHook(function() {
this._latlng = this._bounds.getCenter();
});
// Provide getLatLng and setLatLng methods for
// Leaflet.markercluster to be able to cluster polygons.
L.Polygon.include({
getLatLng: function() {
return this._latlng;
},
setLatLng: function() {} // Dummy method.
});
Updated live example: http://js.do/code/166021

Setup a dynamic var for input Map markers

I have the following function:
$(".mijn_veld").change(function() {
$.getJSON('https://url.com/index.php?action=pslist&zip='+$(".mijn_veld").val()+'&country=NL', function(result){
$.each(result.data, function(i, field){
$(".listings").append(this.name + "<br> ");
});
});
});
This works perfectly. What I want with this function is to add markers on my Google Map. Let say with this function I get the following JSON reponse:
{"status":0,"data":[{"spid":"NL-351202","name":"In 't vosje","add":"Nobelstraat 141","zip":"3512EM","city":"UTRECHT","country":"NL","lon":"5.1246600000","lat":"52.0929748000"},{"spid":"NL-358102","name":"Vivant Verheijen","add":"Burg Reigerstraat 54","zip":"3581KV","city":"UTRECHT","country":"NL","lon":"5.1358400000","lat":"52.0895721000"},{"spid":"NL-351175","name":"Parcelstation deBuren H.Catharijne","add":"Catharijnesingel 11-PS","zip":"3511GB","city":"UTRECHT","country":"NL","lon":"5.1115500000","lat":"52.0922582000"},{"spid":"NL-351403","name":"Vivant De Molen","add":"Adelaarstraat 32","zip":"3514CG","city":"UTRECHT","country":"NL","lon":"5.1158800000","lat":"52.0993884000"},{"spid":"NL-358303","name":"Qualitours","add":"Adr. Van Ostadelaan 41","zip":"3583AA","city":"UTRECHT","country":"NL","lon":"5.1396700000","lat":"52.0832667000"},{"spid":"NL-353103","name":"Ina Ugas 2","add":"Damstraat 64","zip":"3531BW","city":"UTRECHT","country":"NL","lon":"5.1032100000","lat":"52.0922908000"},{"spid":"NL-352203","name":"Cigars N More Utrecht","add":"Rijnlaan 12","zip":"3522BN","city":"UTRECHT","country":"NL","lon":"5.1145300000","lat":"52.0769769000"},{"spid":"NL-357101","name":"Foto Ben Romp","add":"Troosterhof 1","zip":"3571NC","city":"UTRECHT","country":"NL","lon":"5.1356800000","lat":"52.1064315000"},{"spid":"NL-353203","name":"Buurtwinkel Nieuw England","add":"Vleutenseweg 355","zip":"3532HH","city":"UTRECHT","country":"NL","lon":"5.0961200000","lat":"52.0937046000"},{"spid":"NL-355102","name":"Vivant De Plantage","add":"Amsterdamsestraatweg 279","zip":"3551CE","city":"UTRECHT","country":"NL","lon":"5.0989600000","lat":"52.1015290000"},{"spid":"NL-352301","name":"Boek en Kantoor Robman","add":"Smaragdplein 224","zip":"3523EH","city":"UTRECHT","country":"NL","lon":"5.1248600000","lat":"52.0721031000"},{"spid":"NL-356202","name":"The Cartridgers Overvecht","add":"Zamenhofdreef 43","zip":"3562JT","city":"UTRECHT","country":"NL","lon":"5.1120700000","lat":"52.1144018000"},{"spid":"NL-355301","name":"Drogisterij de Kamil","add":"Amsterdamsestraatweg 524","zip":"3553EN","city":"UTRECHT","country":"NL","lon":"5.0844700000","lat":"52.1094875000"},{"spid":"NL-352875","name":"Parcelstation deBuren Utrecht","add":"Papendorpseweg 95-PS","zip":"3528BJ","city":"UTRECHT","country":"NL","lon":"5.0881500000","lat":"52.0629634000"},{"spid":"NL-354203","name":"DHL Parcel Hoofdkantoor","add":"Reactorweg 25","zip":"3542AD","city":"Utrecht","country":"NL","lon":"5.0640800000","lat":"52.1049812000"},{"spid":"NL-354251","name":"DHL Parcelstation Lage weide","add":"Reactorweg 25-PS","zip":"3542AD","city":"UTRECHT","country":"NL","lon":"5.0640800000","lat":"52.1049812000"},{"spid":"NL-354244","name":"Test shop","add":"Reactorweg 25","zip":"3542AD","city":"Utrecht","country":"NL","lon":"5.0640800000","lat":"52.1049812000"},{"spid":"NL-373104","name":"CIGO De Bilt","add":"Hessenweg 162","zip":"3731JN","city":"DE BILT","country":"NL","lon":"5.1817900000","lat":"52.1103054000"},{"spid":"NL-354301","name":"G&W Gezondheidswinkel De Weegschaal","add":"Ella Fitzgeraldplein 34","zip":"3543EP","city":"UTRECHT","country":"NL","lon":"5.0463800000","lat":"52.1015022000"},{"spid":"NL-354202","name":"DHL Parcel Utrecht","add":"Rutherfordweg 1","zip":"3542CN","city":"UTRECHT","country":"NL","lon":"5.0561100000","lat":"52.1204578000"}]}
What I now want is to put this data into a VAR so my script will make markers at my Map. A example is: (But note: I don't want it static like it is now, each time there will be filled in another zipcode with getJSON, it has to update this VAR.)
var stores = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [5.140439, 51.686608]
},
"properties": {
"spid": "NL3700-03",
"name": "Test Parcel 1",
"add": "Teststreet 1",
"zip": "3500RR",
"city": "utrecht",
"country": "NL",
"phone": "032434234",
"oh": "Ma: 12:00 tot 15:00"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [5.133729,51.681425]
},
"properties": {
"phoneFormatted": "(202) 507-8357",
"phone": "2025078357",
"add": "2221 I St NW",
"city": "Washington DC",
"country": "United States",
"crossStreet": "at 22nd St NW",
"postalCode": "20037",
"state": "D.C."
}
}
]
};
My question: How can I make this happen? I want to make sure name value from the JSON output will be in "name" from the VAR STORES. And this for each store there is.
You can load your JSON into an object called places using your first function
var places = {};
$(".mijn_veld").change(function() {
$.getJSON('https://url.com/index.php?action=pslist&zip='+$(".mijn_veld").val()+'&country=NL', function(result) {
places = result;
});
});
Then just loop through the results, adding them to your own data structure as you go. In the example, I set places manually, but for your purposes you can load it from that server.
var places = {
"status":0,
"data":[
{
"spid":"NL-351202",
"name":"In 't vosje",
"add":"Nobelstraat 141",
"zip":"3512EM",
"city":"UTRECHT",
"country":"NL",
"lon":"5.1246600000",
"lat":"52.0929748000"
},
{
"spid":"NL-358102",
"name":"Vivant Verheijen",
"add":"Burg Reigerstraat 54",
"zip":"3581KV",
"city":"UTRECHT",
"country":"NL",
"lon":"5.1358400000",
"lat":"52.0895721000"
},
{
"spid":"NL-351175",
"name":"Parcelstation deBuren H.Catharijne",
"add":"Catharijnesingel 11-PS",
"zip":"3511GB",
"city":"UTRECHT",
"country":"NL",
"lon":"5.1115500000",
"lat":"52.0922582000"
}
]
};
var stores = {
"type": "FeatureCollection",
"features": []
};
for (var i = 0; i < places.data.length; i++) {
var place = places.data[i];
stores.features.push({
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [place.lat, place.lon]
},
properties: {
"spid": place.spid,
"name": place.name,
"add": place.add,
"zip": place.zip,
"city": place.city,
"country": place.country,
}
});
}
console.log(stores);

How to save a GeoJSON into file using javascript

I am wondering if I have a GeoJSON object such as
var geoJSONLoc= {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"timeReported": "2013-01-22 08:42:26+01"
},
"geometry": {
"type": "Point",
"coordinates": [
7.582512743,
51.933292258,
1
]
}
},
{
"type": "Feature",
"properties": {
"timeReported": "2013-01-22 10:00:26+01"
},
"geometry": {
"type": "Point",
"coordinates": [
7.602516645,
51.94962073,
1
]
}
}]}
How can I save this into a .json file for future use?
I am trying to use
localStorage.setItem('geoJSONLoc.json', geoJSONLoc);
but it doesnt seem to be the right answer.
I've done a little work in NodeJS, so this maybe way off base.
But couldn't you use the fs module for this?
something like
var fs = require('fs')
fs.writeFile('geoJSONLoc.json', geoJSONLoc, function(err){
if(err){
console.log(err);
}
});

Categories