How can I get a leaflet.js instance using only a DOM object?

前端 未结 2 433
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-03 00:51

I\'m right now building a custom Knockout.js binding to handle drawing of polygons. In this case the Knockout API only gives me a reference to a DOM object to access whateve

相关标签:
2条回答
  • 2021-01-03 01:13

    As long as you are sure that the DOM element will not be removed, you could just add it as a subproperty on the DOM element itself. Here's a binding handler using the code on the leaflet front page for setting up the leaflet map:

    ko.bindingHandlers.leaflet = {
        init: function(element, valueAccessor){
            var map = L.map(element);
            element.myMapProperty = map;
            L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
                attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            }).addTo(map);
        },
        update: function(element, valueAccessor){
            var existingMap = element.myMapProperty;
            var value = ko.unwrap(valueAccessor());
            var latitude = ko.unwrap(value.latitude);
            var longitude = ko.unwrap(value.longitude);
            var zoom = ko.unwrap(value.zoom);
            existingMap.setView([latitude, longitude], zoom);
        }
    };
    

    To use the binding handler you would just bind like the following:

    <div data-bind="leaflet: { latitude: latitudeProperty, longitude: longitudeProperty, zoom: zoomProperty }"></div>
    

    Just ensure that you have also styled the div to ensure it has a height and width. I have written a jsfiddle which uses the above leaflet bindingHandler where you could try it out.

    I have only tested this jsfiddle in Internet Explorer 11, Firefox 26.0 and Firefox 27.0.1.

    0 讨论(0)
  • 2021-01-03 01:24

    noting that in very limited circumstances, this could be a solution: https://stackoverflow.com/a/60836683/1116657

    window[Object.keys(window).find(key => key.substr(0,3) === "map")];
    

    Read my original post for comments on it's brittleness and limitations, but thought this could be helpful to someone. Thanks!

    0 讨论(0)
提交回复
热议问题