Skip to content

Provide a fetch example #1

Description

@xiaohutai

Here's an example:

Remove the dummy response from index.html, and use the fetch code below instead of the response.forEach.
Update: make a GeoJSON example instead.

location.json
[
    {
        lat: 52.0866,
        lng: 4.2956,
        description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sed vehicula mauris.",
        link: "https://www.vredespaleis.nl",
        title: "Peace Palace"
    },
    {
        lat: 52.0808905,
        lng: 4.3063686,
        description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sed vehicula mauris.",
        link: "https://www.koninklijkhuis.nl",
        title: "Noordeinde Palace"
    }
];

fetch('locations.json')
    .then(function(response) {
        return response.json();
    })
    .then(function(json) {
        json.forEach(function(item){
            let location = new L.LatLng(item.latitude, item.longitude)
            // Spread syntax
            // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
            let options  = {
                icon: icon,
                ...item
            };

            // Leaflet Marker
            // https://leafletjs.com/reference-1.3.2.html#marker
            let marker = new L.marker(location, options);

            // Template literals
            // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
            marker.bindPopup(`
                <h2>${item.title}</h2>
                <p>${item.description}</p>
                <a href='${item.link}'>Read more</a>
            `);
            markers.addLayer(marker);
        }
    });
});

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions