Loading geojson markers into mapbox setting custom icon image

我们两清 提交于 2019-12-02 03:54:16

I guess it's a typical beginners mistake and maybe it's just me but I found it pretty confusing in which context to use the several options of setIcon. In the end I made it work using .on(layeradd) and marker.setIcon(pathToYourIcon).

ma_3.on('layeradd', function(layer) {
            this.eachLayer(function(marker) {
        if (marker.toGeoJSON().properties.title === 'Verpflegung') {
            marker.setIcon(icon_live);
        } 

        marker.bindPopup(marker.toGeoJSON().properties.id + ', ' +
            marker.toGeoJSON().properties.title);
    });
});

Have you seen this example yet?

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Custom marker icons</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.mapbox.com/mapbox.js/v2.2.2/mapbox.js'></script>
<link href='https://api.mapbox.com/mapbox.js/v2.2.2/mapbox.css' rel='stylesheet' />
<style>
  body { margin:0; padding:0; }
  #map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<div id='map'></div>
<script>
L.mapbox.accessToken = '<your access token here>';
var map = L.mapbox.map('map', 'mapbox.streets')
    .setView([40, -74.50], 8);

var myLayer = L.mapbox.featureLayer().addTo(map);

var geoJson = [{
    "type": "Feature",
    "geometry": {
        "type": "Point",
        "coordinates": [-75.00, 40]
    },
    "properties": {
        "title": "Small astronaut",
        "icon": {
            "iconUrl": "/mapbox.js/assets/images/astronaut1.png",
            "iconSize": [50, 50], // size of the icon
            "iconAnchor": [25, 25], // point of the icon which will correspond to marker's location
            "popupAnchor": [0, -25], // point from which the popup should open relative to the iconAnchor
            "className": "dot"
        }
    }
}, {
    "type": "Feature",
    "geometry": {
        "type": "Point",
        "coordinates": [-74.00, 40]
    },
    "properties": {
        "title": "Big astronaut",
        "icon": {
            "iconUrl": "/mapbox.js/assets/images/astronaut2.png",
            "iconSize": [100, 100],
            "iconAnchor": [50, 50],
            "popupAnchor": [0, -55],
            "className": "dot"
        }
    }
}];

// Set a custom icon on each marker based on feature properties.
myLayer.on('layeradd', function(e) {
    var marker = e.layer,
        feature = marker.feature;

    marker.setIcon(L.icon(feature.properties.icon));
});

// Add features to the map.
myLayer.setGeoJSON(geoJson);
</script>
</body>
</html>

*Source: https://www.mapbox.com/mapbox.js/example/v1.0.0/custom-marker/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!