简体   繁体   中英

Building leaflet GeoJson with $.each loop

I am attempting to build a GeoJson LineString using a $.each loop. However, I can't seem to work it out.

From the information I have read this should be working.

What am I doing wrong?

var geojson = {
  type: 'LineString',
  coordinates: []
};

        $.each(data, function(key, data) { 
    geojson.coordinates.push(data.shape_pt_lat.toString(),data.shape_pt_lon.toString());
          });
console.log(geojson.coordinates.toString());
L.geoJson(geojson).addTo(map_osm);

Console.log Output is

-36.861461,174.750440,-36.860228,174.751980,-36.859726,174.752736,-36.858892,174.753709,-36.858594,174.754863,-36.858037,174.756671,-36.857528,174.758350,-36.857694,174.759050,-36.855159,174.758675,-36.854423,174.759160,-36.851987,174.760902,-36.851186,174.761970,-36.851037,174.762303,-36.850380,174.762700,-36.849411,174.763020,-36.848521,174.763507,-36.847178,174.764000,-36.845462,174.764750,-36.843594,174.767050

Error Message:

Error: Invalid LatLng object: (3, NaN)

If I user the below:

geojson.coordinates.push([data.shape_pt_lat,data.shape_pt_lon]);

It displays a line, however it is on the top middle of the map, and nowhere near the coordinates entered.

Console output for this is:

[["-36.857694", "174.759050"], ["-36.855159", "174.758675"], ["-36.854423", "174.759160"], ["-36.851987", "174.760902"], ["-36.851186", "174.761970"], ["-36.851037", "174.762303"], ["-36.850380", "174.762700"], ["-36.849411", "174.763020"], ["-36.848521", "174.763507"], ["-36.847178", "174.764000"], ["-36.845462", "174.764750"], ["-36.843594", "174.767050"]]

You have to make the points as [lon,lat] not [lat,lon]. Additionally, write the numbers as float, not as string (removing the quotes). You could test the validity in http://geojsonlint.com/ Example for your data:

{
"type": "LineString",
"coordinates": [[-36.857694, 174.759050], [-36.855159, 174.758675], [-36.854423, 174.759160], [-36.851987, 174.760902], [-36.851186, 174.761970], [-36.851037, 174.762303], [-36.850380, 174.762700], [-36.849411, 174.763020], [-36.848521, 174.763507], [-36.847178, 174.764000], [-36.845462, 174.764750], [-36.843594, 174.767050]]

}

Example with correct data

{
"type": "LineString",
"coordinates": [[174.759050, -36.857694], [174.758675, -36.855159], [174.759160, -36.854423], [174.760902, -36.851987], [174.761970, -36.851186], [174.762303, -36.851037], [174.762700, -36.850380], [174.763020, -36.849411], [174.763507, -36.848521], [174.764000, -36.847178], [174.764750, -36.845462], [174.767050, -36.843594]]

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM