1

I am new to Leafletjs and I am trying to figure out how to plot a polyline on a map using a geoJson object. I've gotten as far as getting a map, making it centered on a given lat/long and setting the zoom. However, I cannot determine how to display the lines using geoJson data.

I confirmed that the coordinates work - I was able to plot them using the Leaflet polyline layer.

<html>
<head>
<title>Leaflet GeoJSON Example</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="leaflet.css" />
</head>
<body>
    <div id="map" style="width: 900px; height: 700px"></div>
    <script src="leaflet.js"></script>
    <script>
        var center = [42.454873, -71.125094];
        var map = L.map('map').setView(center, 15);
        L.tileLayer('http://otile1.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a>contributors'}).addTo(map);

        var myLines = [{
            "type": "LineString",
            "coordinates": [[42.438917, -71.116146],[42.443904, -71.122044]]
        }, {
            "type": "LineString",
            "coordinates": [[42.447298, -71.121447],[42.454873, -71.125094],[42.459079, -71.124988]]
        }];

        var myStyle = {
            "color": "#ff7800",
            "weight": 5,
            "opacity": 0.65
        };

        L.geoJson(myLines, {style: myStyle}).addTo(map);

    </script>
</body>
</html>

1 Answer 1

3

In your code, myLines is not a geojson structure ...

Try with this syntax

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "LineString",
        "coordinates": [[42.438917, -71.116146],[42.443904, -71.122044]]
      }
    },
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "LineString",
        "coordinates": [[42.447298, -71.121447],[42.454873, -71.125094],[42.459079, -71.124988]]
      }
    }
  ]
}

To write proper geojson you can use: http://geojson.io/

1
  • nice link. will have to use that. i've found jsonlint.com to also be helpful in pointing out syntax errors. Commented Oct 18, 2014 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.