如何在 Polymer 1.0 / leaflet-map 1.0 中使用 map.locate

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

我是 Polymer 和 Leaflet 的网络组件的新手。

我想要一个按钮来切换 Leaflet 提供的地理定位功能。在 Javascript/HTML/css 应用程序中使用 Leaflet 我会知道如何执行此操作,但我无法使用 Polymer 1.0 使其工作。

这是我的地图元素。我尝试调用 map.locate 在元素注册中被注释掉了:

<dom-module id="my-maps">
 <style>
   ...
 </style>
  <template>
    <leaflet-map id="thismap" latitude="{{latitude}}" longitude="{{longitude}}" zoom="14"> 
      <leaflet-geolocation enable-high-accuracy latitude="{{latitude}}" longitude="{{longitude}}" watch="true">
      </leaflet-geolocation>     
      <template is="dom-if" if="{{latitude}}">
        <leaflet-marker latitude="{{latitude}}" longitude="{{longitude}}">                 
        </leaflet-marker>
      </template>
    </leaflet-map>
  </template>
  <script>
     Polymer({
      is: "my-maps",
      ready: function () {
           L.Icon.Default.imagePath="../../bower_components/leaflet/dist/images";      
           // **this.$.thismap.locate({setView: true}); // not working**
       } 

   });
  </script>
</dom-module>

对于这个例子,我得到了这个错误: 无法读取未定义的 属性 'thismap'

如果我直接引用'this'(this.locate()),返回的错误是: this.locate 不是函数

(此片段只是一个测试;理想情况下,定位函数将由 'geoButton' 元素的点击事件调用):

      <div flex>
           <ir-maps id="mymap" class="basemap" flex></ir-maps> 
           <ir-geoButton class="geoButton" ></ir-geoButton>
      </div>

我的解决方案没有明确使用 map.locate。这不是必需的,因为 map.locate 通过添加 leaflet-geolocation 元素启用。

我从 leaflet-map 元素中删除了纬度和经度 属性(并添加了一些其他参数):

        <leaflet-map 

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

然后我在 leaflet-map 元素 (leaflet-core.html) 的注册中添加了一个一次性监听器,这样如果启用了地理定位,地图将缩放到该位置,如果它是不是它会缩放到默认的中心点。 'geoB' 是一个切换地理定位功能的按钮:

            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);

我向 leaflet-map 元素添加了另一个函数,以便我可以将当​​前的纬度和经度传递给元素并缩放到该点,单击地理定位按钮:

    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();
           });

        }

    },

最后,这个函数在 geoButton 元素的事件侦听器中被调用,它引用了 leaflet-geolocation 元素:

nycmap.setToPoint(locator.latitude, locator.longitude);