darnton / LeafletBlazor

Blazor component for interop with Leaflet slippy map library.
30 stars 20 forks source link

Two components on the same page? #1

Open Velobook opened 3 years ago

Velobook commented 3 years ago

I am testing your interesting component .It works fine with your demo. But if we put 2 components on the same page we got an error : _Unhandled exception rendering component: Map container is already initialized. How to proceed to use more than a component on one page?

darnton commented 3 years ago

You can do this if you have two separate Map instances. Try something like this: In your component's .razor file:

<div class="my-3">
    <LeafletMap Map="FirstMap" TileLayer="OpenStreetMapsTileLayer" />
</div>
<div class="my-3">
    <LeafletMap Map="SecondMap" TileLayer="OpenStreetMapsTileLayer" />
</div>

and in the code-behind / .razor.cs file:

        public MyTestComponentBase() : base()
        {
            FirstMap = new Map("firstMapElementId", new MapOptions
            {
                Center = new LatLng(-42, 175),
                Zoom = 4
            });
            SecondMap = new Map("secondMapElementId", new MapOptions
            {
                Center = new LatLng(-42, 175),
                Zoom = 4
            });
            OpenStreetMapsTileLayer = new TileLayer(
                "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
                new TileLayerOptions
                {
                    Attribution = @"Map data &copy; <a href=""https://www.openstreetmap.org/"">OpenStreetMap</a> contributors, " +
                        @"<a href=""https://creativecommons.org/licenses/by-sa/2.0/"">CC-BY-SA</a>"
                }
            );
        }

Let me know if that doesn't work.

(It may also pay to stick with the master branch for the moment. I've found a couple of problems on the dotnet5 branch.)

darnton commented 3 years ago

If there are still problems, try creating two tile layers rather than reusing the same for both maps.

darnton commented 3 years ago

I've just updated the dotnet5 branch to simplify the client code. All of the JS binding stuff is better contained and hidden from the client now.