How to use LeafletJS Map in a Symfony Project?

I’m new to Symfony and I’m trying to build a simple game based on maps.
I started with the homepage with should show an adress input field and below a map therefore I have created home.html.twig file in the templates/app folder and added this code that should work (I tested it independently when I wasn’t working with Symfony) but it doesn’t show the map!

The console log shows me this error:

Map.js:1103 Uncaught Error: Map container not found. at
i._initContainer (Map.js:1103) at initialize (Map.js:136) at new i
(Class.js:22) at Object.t.map (Map.js:1728) at (index):14

Here’s the code of my home.html.twig:

<html>
    <head>
        <title>XD</title>
        <meta charset="utf-8">
        {% block stylesheets %} <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
        integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
        crossorigin=""/>{% endblock %}
         {% block javascripts %}
            <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
            integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
            crossorigin=""></script>
            <script type="text/javascript">
            console.log("hola!");
            var adresse=document.getElementById("adresse");
            var centerview=[46.71109,1.7191036];
            var mymap = L.map('carte1').setView([centerview[0], centerview[1]], 6);
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            }).addTo(mymap);
            var layerGroup = L.layerGroup().addTo(mymap);
            adresse.addEventListener('input',e=>{
                console.log(adresse.value);
                var query="http://api-adresse.data.gouv.fr/search/?q="+adresse.value;
                fetch(query,{method: 'get'})
                .then(r=>r.json())
                .then(r=>{
                    layerGroup.clearLayers();
                    r.features.forEach(element => {
                        var coords=element.geometry.coordinates;
                        L.marker([coords[1],coords[0]]).addTo(layerGroup);
                    });
                })
            })

            </script>
        {% endblock %}
    </head>
    <body>
        <form id="fff" action="#">
            <input type="text" placeholder="Entrez une adresse" id="adresse"/>
        </form>

        <div id="carte1" style="height: 300px;">
        </div>
        <div id="coords" style="position: absolute; z-index: 3; top: auto; left: auto;"></div>
        
        
    </body>

</html>

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *