2
votes

I'm trying to move my L.polygon data to a different file. I'm using jQuery to get the data from the separate file. It seems like it should be returning the exact same data I was using when I had it as a L.polygon in the index.html file, but instead it's returning this error:

Invalid LatLng object: ( , undefined) 

I searched for the error, but it seems that everyone else who has reported it was using a different data type than I am.

Here's the full example:

index.html:

<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
  <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" />
  <script src="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
  <style type="text/css">
  #map {
    height: 500px;
  }
  </style>
</head>
<body>

<div id="map"></div>
<script type="text/javascript">
  var map = L.map('map').setView([33.720818, -84.240], 11);

  $.get("data/temp.csv", function(data) {
    console.log(data);
    var temp = new L.polygon(data).setStyle(defaultStyle).addTo(map);
  });
</script>

</body>
</html>

data/temp.csv:

[
[33.829205,-84.377261],
[33.829121,-84.377257],
[33.829039,-84.377271],
[33.828937,-84.377204],
[33.828871,-84.377122]
]

Edit: To clarify, adding the following to the index.html file works just fine, but bringing it in from another file (above) isn't working.

var temp = L.polygon([
  [33.829205,-84.377261],
  [33.829121,-84.377257],
  [33.829039,-84.377271],
  [33.828937,-84.377204],
  [33.828871,-84.377122]
  ]).setStyle(defaultStyle).addTo(map);
2
data here is might be a string, meaning that you're doing L.polygon("[...]") instead of L.polygon([...]). Maybe try $.getJSON instead of $.get, or do data = $.parseJSON(data);.apsillers

2 Answers

4
votes

L.polygon() expects an array of LatLng objects.

You need to either iterate over the array, creating a LatLng out of each of those elements, or wrap this list in a GeoJSON object and use the GeoJSON class to do that for you.

Something like:

L.geoJson({"type": "Polygon", "coordinates": data}).setStyle(defaultStyle).addTo(map);

edit from comments: It turns out that L.polygon() does actually convert an array of arrays to an array of LatLng automatically. The problem was instead that you need to be explicit and pass in "json" as the last argument to $.get() in order to ensure that it's actually parsing the string as JSON, rather than returning the raw string.

0
votes

You can use JSON.parse(data) .for me,it works.