简体   繁体   English

单击传单设置标记图标

[英]Leaflet set marker icon on click

I'm trying to change geojson marker icon on click following various exemple found on the web but I can't get it to work, it raise this error message: 我正在尝试更改在网络上找到的各种示例后的点击时更改geojson标记图标,但我无法使其正常工作,这会引发以下错误消息:

TypeError: e.target.setIcon is not a function

Bellow the snippet 摘录片段

    var map = L.map('map',{ center: [44.1, 3.5], zoom: 10});
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: 'OpenStreetMap'}).addTo(map);

    var icon = L.icon({
        iconUrl: 'https://cdn1.iconfinder.com/data/icons/Map-Markers-Icons-Demo-PNG/256/Map-Marker-Marker-Outside-Azure.png',
        iconSize: [ 48, 48 ],
    });

    var data = {
    "type": "FeatureCollection",
    "name": "test",
    "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
    "features": [
        { "type": "Feature", "properties": { "NUM": 1 }, "geometry": { "type": "MultiPoint", "coordinates": [ [ 3.75, 44.25 ] ] } },
        { "type": "Feature", "properties": { "NUM": 2 }, "geometry": { "type": "MultiPoint", "coordinates": [ [ 3.25, 44.0 ] ] } }
    ]}

    L.geoJson(data,{

      pointToLayer: function (feature, latlng) {
          return L.marker(latlng);//, {icon: icon});
      },
      onEachFeature: function (feature, layer) {
          layer.on('click', function (e){
            e.target.setIcon(icon);
          })
      }
    }).addTo(map);

what's wrong? 怎么了?

The issue is originating from the GeoJSON. 问题出自GeoJSON。 It does seem to be a valid GeoJSON because it plots on the map, but it must be tripping up Leaflet somehow. 它似乎确实是有效的GeoJSON,因为它在地图上进行绘制,但是它一定会以某种方式绊倒Leaflet。 I think the fact that it's a MultiPoint feature is the cause. 我认为这是MultiPoint功能的事实。

Changing the GeoJSON to: 将GeoJSON更改为:

var data = {
    "type": "FeatureCollection",
    "name": "test",
    "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
    "features": [
        { "type": "Feature", "properties": { "NUM": 1 }, "geometry": { "type": "Point", "coordinates": [ 3.75, 44.25 ] } },
        { "type": "Feature", "properties": { "NUM": 2 }, "geometry": { "type": "Point", "coordinates": [ 3.25, 44.0 ] } }
]}

makes it work. 使它工作。 (Note: I just changed "type" from MultiPoint to Point and removed the double brackets, ie [ [ 3.25, 44.0 ] ] became [ 3.25, 44.0 ] .) (注意:我只是将"type"MultiPoint更改为Point并删除了双括号,即[ [ 3.25, 44.0 ] ]变为[ 3.25, 44.0 ] 。)

I'm not sure if it's possible to use MultiPoint geometry with the onEachFeature function, but it seems to be working with single point geometry. 我不确定是否可以在onEachFeature函数中使用MultiPoint几何体,但是似乎可以使用单点几何体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM