单击上的单张设置标记图标

时间:2017-08-09 16:18:27

标签: javascript leaflet geojson

我正在尝试更改geojson标记图标,点击网上找到的各种例子,但我无法让它工作,它会引发此错误消息:

TypeError: e.target.setIcon is not a function

警告片段

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

出了什么问题?

1 个答案:

答案 0 :(得分:0)

问题源于GeoJSON。它看起来似乎是一个有效的GeoJSON,因为它在地图上绘制,但它必须以某种方式绊倒Leaflet。我认为这是一个MultiPoint功能的原因。

将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 ] } }
]}

让它发挥作用。 (注意:我刚刚将"type"MultiPoint更改为Point并删除了双括号,即[ [ 3.25, 44.0 ] ]变为[ 3.25, 44.0 ]。)

我不确定是否可以将MultiPoint几何与onEachFeature函数一起使用,但它似乎与单点几何一起使用。

相关问题