admin管理员组

文章数量:1296316

I am very new in my learnings of javascript and my rudimentary knowledge has hit a wall. I have setup a Leaflet map which I am wishing to plot divIcon based markers from cords on it from JSON. Through my countless research of trying to get it to work. I learned why my JSON file wasn't working even though I confirmed in the console it was being read. I learned Leaflet prefers it to be in GeoJSON. So I spent several more hours researching how to convert this. Most of my findings were outdated and did not work anymore or did not apply to me. This is what I did try through my rigorous research.

To start off I have set a variable for the path to my test JSON file as defined like this.

var jsonData = "./data/tracking.json";

In my attempt to convert the JSON to GeoJSON I tried this.

var outGeoJson = {}
outGeoJson['properties'] = jsonData
outGeoJson['type']= "Feature"
outGeoJson['geometry']= {"type": "Point", "coordinates":
    [jsonData['lat'], jsonData['lon']]}

console.log(outGeoJson)

Checked the console and found the coordinates in the array from JSON file are undefined.

My search for a reason why this was ing up undefined fell short. My theory here is maybe because the JSON has a key of positions prior to the array and the fact it is an array. I continue to search for a valid solution that could possibly handle this issue. I tried this solution next.

var geojson = {
  type: "FeatureCollection",
  features: [],
};

for (i = 0; i < jsonData.positions.length; i++) {
  if (window.CP.shouldStopExecution(1)) {
    break;
  }
  geojson.features.push({
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [jsonData.positions[i].longitude, jsonData.positions[i].latitude]
    },
    "properties": {
      "report_at": jsonData.positions[i].report_at,
      "lat": jsonData.positions[i].lat,
      "lon": jsonData.positions[i].lon,
      "dir": jsonData.positions[i].dir,
      "first": jsonData.positions[i].first,
      "last": jsonData.positions[i].last
    }
  });
}

window.CP.exitedLoop(1);

console.log(geojson)

This solution gave me an error in the console of Uncaught TypeError: Cannot read property 'length' of undefined.

Attempted to troubleshoot that solution for several more hours and that has fallen short as well. Here is a sample of the test JSON file I am working with.

{
  "positions": [
    {
      "report_at": "2015-01-21 21:00:08",
      "lat": "38.9080658",
      "lon": "-77.0030365",
      "elev": "0",
      "dir": "0",
      "gps": "0",
      "callsign": "WX2DX",
      "email": "",
      "phone": "",
      "ham": "WX2DX",
      "ham_show": "0",
      "freq": "",
      "note": "",
      "im": "",
      "twitter": null,
      "web": "",
      "unix": "1421874008",
      "first": "William",
      "last": "Smith",
      "marker": "36181"
    }
  ]
}

All I really need from it is the report_at, lat, lon, dir, first, last anyways. The rest I can do without. Is the above mentioned examples I tried a good or proper way to convert it? If not, then does anyone have a better suggestion than what I have been trying that I might be missing or overlooking which is a pretty good possibility due to be very green to this language? Thanks in advance!

EDIT: Since it has been brought to my attention I am not loading the JSON file this is what I have done to load it since the suggestions do not work as they apply to node.js and not a part of native javascript.

    $.getJSON("./data/tracking.json", function(jsonData) {
  var outGeoJson = {}
  outGeoJson['properties'] = jsonData
  outGeoJson['type']= "Feature"
  outGeoJson['geometry']= {"type": "Point", "coordinates":
      [jsonData['lat'], jsonData['lon']]}

  console.log(outGeoJson)
});

This does load the file as it is displaying in the console as converted to GeoJSON. I will leave this as is for now unless there is a better solution.

I am very new in my learnings of javascript and my rudimentary knowledge has hit a wall. I have setup a Leaflet map which I am wishing to plot divIcon based markers from cords on it from JSON. Through my countless research of trying to get it to work. I learned why my JSON file wasn't working even though I confirmed in the console it was being read. I learned Leaflet prefers it to be in GeoJSON. So I spent several more hours researching how to convert this. Most of my findings were outdated and did not work anymore or did not apply to me. This is what I did try through my rigorous research.

To start off I have set a variable for the path to my test JSON file as defined like this.

var jsonData = "./data/tracking.json";

In my attempt to convert the JSON to GeoJSON I tried this.

var outGeoJson = {}
outGeoJson['properties'] = jsonData
outGeoJson['type']= "Feature"
outGeoJson['geometry']= {"type": "Point", "coordinates":
    [jsonData['lat'], jsonData['lon']]}

console.log(outGeoJson)

Checked the console and found the coordinates in the array from JSON file are undefined.

My search for a reason why this was ing up undefined fell short. My theory here is maybe because the JSON has a key of positions prior to the array and the fact it is an array. I continue to search for a valid solution that could possibly handle this issue. I tried this solution next.

var geojson = {
  type: "FeatureCollection",
  features: [],
};

for (i = 0; i < jsonData.positions.length; i++) {
  if (window.CP.shouldStopExecution(1)) {
    break;
  }
  geojson.features.push({
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [jsonData.positions[i].longitude, jsonData.positions[i].latitude]
    },
    "properties": {
      "report_at": jsonData.positions[i].report_at,
      "lat": jsonData.positions[i].lat,
      "lon": jsonData.positions[i].lon,
      "dir": jsonData.positions[i].dir,
      "first": jsonData.positions[i].first,
      "last": jsonData.positions[i].last
    }
  });
}

window.CP.exitedLoop(1);

console.log(geojson)

This solution gave me an error in the console of Uncaught TypeError: Cannot read property 'length' of undefined.

Attempted to troubleshoot that solution for several more hours and that has fallen short as well. Here is a sample of the test JSON file I am working with.

{
  "positions": [
    {
      "report_at": "2015-01-21 21:00:08",
      "lat": "38.9080658",
      "lon": "-77.0030365",
      "elev": "0",
      "dir": "0",
      "gps": "0",
      "callsign": "WX2DX",
      "email": "",
      "phone": "",
      "ham": "WX2DX",
      "ham_show": "0",
      "freq": "",
      "note": "",
      "im": "",
      "twitter": null,
      "web": "",
      "unix": "1421874008",
      "first": "William",
      "last": "Smith",
      "marker": "36181"
    }
  ]
}

All I really need from it is the report_at, lat, lon, dir, first, last anyways. The rest I can do without. Is the above mentioned examples I tried a good or proper way to convert it? If not, then does anyone have a better suggestion than what I have been trying that I might be missing or overlooking which is a pretty good possibility due to be very green to this language? Thanks in advance!

EDIT: Since it has been brought to my attention I am not loading the JSON file this is what I have done to load it since the suggestions do not work as they apply to node.js and not a part of native javascript.

    $.getJSON("./data/tracking.json", function(jsonData) {
  var outGeoJson = {}
  outGeoJson['properties'] = jsonData
  outGeoJson['type']= "Feature"
  outGeoJson['geometry']= {"type": "Point", "coordinates":
      [jsonData['lat'], jsonData['lon']]}

  console.log(outGeoJson)
});

This does load the file as it is displaying in the console as converted to GeoJSON. I will leave this as is for now unless there is a better solution.

Share edited Apr 28, 2019 at 8:57 DFW Storm Force asked Apr 28, 2019 at 7:06 DFW Storm ForceDFW Storm Force 1231 gold badge1 silver badge8 bronze badges 2
  • 1 Note that you set the jsonData variable to just a path string. You never show any code actually loading the data (eg from that file). Just setting some variable to some path doesnt magically load it. You can see this as you set the properties property to your jsonData variable and in the console log properties is showing as that path string... so jsonData doesnt hold your data but instead just some string. Make sure you are loading/assigning the data to your variable – Patrick Evans Commented Apr 28, 2019 at 7:11
  • I posted the var jsonData as reference so you would know what that variable was as posted in the two code examples to show it was being loaded. I see what you're saying and it does make sense. Based on some of the questions I came across and tutorials, that is how they were loading the data file. I am a little confused because if it wasn't loading the data then why is it showing an array of two entries, which is exactly how many entries is in that JSON file? – DFW Storm Force Commented Apr 28, 2019 at 7:59
Add a ment  | 

2 Answers 2

Reset to default 4

If you do have jQuery in your project added, then you are almost there:

$.getJSON("./data/tracking.json", function(jsonData) {
    /* 
    Here the anonymous function is called when the file has been downloaded.
    Only then you can be sure that the JSON data is present and you can work with it's data.
    You have to keep in mind if you are getting the file synchronously or asynchronously (default).
   */
});

var jsonData = "./data/tracking.json";

try replacing this with the next line.

var jsonData = require("./data/tracking.json"); or

import jsonData from "./data/tracking.json"; #es6 style

as @PatrickEvans mentioned you have to actually load the data rather than giving path as a string.

本文标签: javascriptHow to convert JSON to GeoJSONStack Overflow