how to use map.locate with Polymer 1.0 / leaflet-map 1.0

后端 未结 1 1817
情深已故
情深已故 2021-01-24 03:56

I am new to both Polymer and Leaflet\'s web component.

I would like to have a button that toggles the geolocation function given by Leaflet. Using Leaflet in a Javascri

相关标签:
1条回答
  • 2021-01-24 04:17

    My solution does not use map.locate explicitly. This was not needed, as map.locate is enabled by adding the leaflet-geolocation element.

    I removed the latitude and longitude property from the leaflet-map element (and added a few other parameters):

            <leaflet-map 
    
            id="nycmap" zoom="14" 
            min-zoom="14" 
            max-zoom="18" 
            nozoomControl="true"
            noattributionControl:="false">
    

    Then I added a one-time listener to the registration of the leaflet-map element (leaflet-core.html), so that if geolocation is enabled, the map will zoom to that location, and if it is not it will zoom to a default center point. 'geoB' is a button that toggles the geolocation function:

                map.addOneTimeEventListener('locationfound', function (e){
    
                console.log("get to located found?");           
                map.setView(L.latLng(e.latitude, e.longitude), 14);
                var geo = document.getElementById('geoB');
                var state = geo.classList.toggle('toggleState');
            }, this);
    
    
    
            map.on('locationerror', function(e){
                console.log("get to located error?");
                map.setView(L.latLng(40.6889, -73.9444), 14);
                map.stopLocate();
            }, this);
    

    I added another function to the leaflet-map element so that I can pass the current latitude and longitude to the element and zoom to that point, on the click on the geolocation button:

        setToPoint: function(newLat, newLong){
            if (this.map && !this._ignoreViewChange) {
                this.async(function() {
                   this.map.setView(L.latLng(newLat, newLong), this.zoom, {pan: {animate: true}});
                   this.map.invalidateSize();
               });
    
            }
    
        },
    

    Finally, this function is called in an event listener in the geoButton element, which references the leaflet-geolocation element:

    nycmap.setToPoint(locator.latitude, locator.longitude);
    
    0 讨论(0)
提交回复
热议问题