0
votes

I just started working with Leaflet. I want to create a map for a game, so this is a map created with L.CRS.Simple.

I have been able to set the map image, and add marker manually.

Now, I want to create markers and layers groups dynamicly from a json file that I generate in PHP from a sqlite database.

My json is this one for now : https://grounded.dubebenjamin.com/api/markers.json

My json is a list of type(layergroup) inside which I have put another object containing all the markers for the type(layergroup) :

Structure :

{
  "landmarks": {
    "id": 1,
    "slug": "landmark",
    "type": "Landmarks",
    "markers": [
      {"id": 1, "title": "Title of marker 1 of layergroup1"},
      {"id": 2, "title": "Title of marker 2 of layergroup1"}
    ]
  },
  "science": {
    "id": 2,
    "slug": "science",
    "type": "Science Points",
    "markers": [
      {"id": 1, "title": "Title of marker 1 of layergroup2"}
    ]
  }
}
  • = Where landmarks and science are layergroup.

From this json, my plan was to have a first loop, where for each type I want to create a layer group, then create the markers for this layer group and assign the markers to the layer groups.

Manually, I understand the usage of L.marker and L.layerGroup, but where I am stuck, is how to do that in a loop, and defined the layoutgroup name from the json data.

From now, I have just been able to create the marker, but not the layer group. You can see my progress here: https://grounded.dubebenjamin.com/

If you need more precision, just ask me.

1

1 Answers

2
votes

Use this code:

var layergroups = {};
fetch('https://grounded.dubebenjamin.com/api/markers.json').then(response => response.json())
    .then((data)=>{
        layergroups = {};
        for(type in data){
            var lg = L.layerGroup().addTo(map)
            layergroups[type] = lg;
            if(data[type].markers){
                var markers = data[type].markers;
                markers.forEach((marker)=>{
                    L.marker([marker.x,marker.y]).bindPopup(marker.desc).addTo(lg);
                })
            }
        }
    })

First fetch the data from the server, then loop through the layergroups and add them to the map and then to the Object/Array. Then you create the markers and add them to the layergroup.

You can get the layergroups over the Object layergroups but keep in mind that the request is async.