简体   繁体   中英

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:

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. It does seem to be a valid GeoJSON because it plots on the map, but it must be tripping up Leaflet somehow. I think the fact that it's a MultiPoint feature is the cause.

Changing the GeoJSON to:

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 ] .)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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