1

I tried to load geojson file into my map. my geojson file is located in another folder called "data" and name of geojson is "street.json". I want to load this data to my leaflet map. how is possible? I tried the following code:

L.geoJSON('data/street.json').addTo(map);
kboul
  • 13,836
  • 5
  • 42
  • 53
Tek Kshetri
  • 2,129
  • 1
  • 17
  • 41

1 Answers1

2

If you use es6 you can use

import street from "./data/street.json"; where street is your geojson file

and then use L.geoJSON(street).addTo(map)

Here is an es6 example with a geojson to see it live.

Edit

Without using es6 what you need to do is:

Having created a folder data and a file street.json you need to store the json inside street.json with a variable for instance

var street = {
    "type": "FeatureCollection",
    "features": [
       {
          "type": "Feature",
          "geometry": {
          "type": "LineString",
          "coordinates": [
              [-105.00341892242432, 39.75383843460583],
              [-105.0008225440979, 39.751891803969535]
          ]
       },
       ...
}

and then import it on index.html as

<script src="./data/street.json"></script>

inside <body>. Make sure you create the folder inside the root of your project.

Therefore you would have something like this in your body:

<body>
    <div id="map"></div>
    <script src="./data/street.json"></script>

    <script src="script.js"></script>

</body>

and then reference it with the variable street you defined inside street.json:

L.geoJSON(street).addTo(map)

plain js demo

kboul
  • 13,836
  • 5
  • 42
  • 53
  • Thank you for your solution. But I am not familiar with es6. I have to do it from JavaScript or jquery. Is there any other idea? – Tek Kshetri May 19 '19 at 13:18
  • I edited my answer and included also an example without using es6 – kboul May 19 '19 at 13:47
  • 1
    Thank you ! I found my mistake. I didn't mention the variable 'street' in my street.json file, so this error was occurred. – Tek Kshetri May 19 '19 at 17:30