добавление и использование переменной маркера с помощью geoJsonData и markercluster с leaflet.js

Я искал часы и часы, и я все еще застрял. У меня такое чувство, что это что-то простое/глупое, чего мне не хватает.

Я использую пример markercluster из GitHub. У меня есть 2 разных маркера (просто 2 разных цвета), которые я хотел бы показать, которые я бы определил в формате json. Я следовал руководству с сайта листовок, чтобы определить различные маркеры. Я добавил свою переменную в часть json, но не могу понять, как заставить карту загружать разные маркеры. Это либо не дает мне карту, либо ошибку; или он по-прежнему использует синий маркер по умолчанию.

вот мой код:

<script type="text/javascript">

        var geoJsonData = {
            "type": "FeatureCollection",
            "features": [
                { "type": "Feature", "id":"1", "properties": { "address": "2","marker": "cmIcon"}, "geometry": { "type": "Point", "coordinates": [175.2209316333,-37.8210922667 ] } },
                { "type": "Feature", "id":"2", "properties": { "address": "151","marker": "otherIcon" }, "geometry": { "type": "Point", "coordinates": [175.2238417833,-37.80975435   ] } },
                { "type": "Feature", "id":"3", "properties": { "address": "21","marker": "cmIcon"  }, "geometry": { "type": "Point", "coordinates": [175.2169955667,-37.818193     ] } },
                { "type": "Feature", "id":"4", "properties": { "address": "14","marker": "otherIcon"  }, "geometry": { "type": "Point", "coordinates": [175.2240856667,-37.8216963    ] } },
                { "type": "Feature", "id":"5", "properties": { "address": "38B","marker": "cmIcon" }, "geometry": { "type": "Point", "coordinates": [175.2196982333,-37.8188702167 ] } },
                { "type": "Feature", "id":"6", "properties": { "address": "38","marker": "otherIcon"  }, "geometry": { "type": "Point", "coordinates": [175.2209942   ,-37.8192782833 ] } }
            ]
        };

        var cloudmade = L.tileLayer('http://{s}.tile.cloudmade.com/{key}/997/256/{z}/{x}/{y}.png', {
            maxZoom: 18,
            attribution: 'Map data &copy; 2011 OpenStreetMap contributors, Imagery &copy; 2011 CloudMade',
            key: 'BC9A493B41014CAABB98F0471D759707'
        });

        var LeafIcon = L.Icon.extend({
            options: {
                shadowUrl: 'marker/marker-shadow.png',
                iconSize:     [32, 32],
                shadowSize:   [36, 20],
                iconAnchor:   [22, 94],
                shadowAnchor: [4, 62],
                popupAnchor:  [-3, -76]
            }
        });

        var cmIcon = new LeafIcon({iconUrl: 'marker/marker-cm.png'}),
            otherIcon = new LeafIcon({iconUrl: 'marker/marker-others.png'});

        var map = L.map('map')
                .addLayer(cloudmade);

        var markers = new L.MarkerClusterGroup();

        var geoJsonLayer = L.geoJson(geoJsonData, {
            onEachFeature: function (feature, layer) {
                layer.bindPopup(feature.properties.address);
            }
        });
        markers.addLayer(geoJsonLayer);

        map.addLayer(markers);
        map.fitBounds(markers.getBounds());

        function onLocationFound(e) {
                    var radius = e.accuracy / 2;

                    L.marker(e.latlng).addTo(map)
                        .bindPopup("Vous etes ici").openPopup();

                    L.circle(e.latlng, radius).addTo(map);
                }

                function onLocationError(e) {
                    alert(e.message);
                }

                map.on('locationfound', onLocationFound);
                map.on('locationerror', onLocationError);

                map.locate({setView: true, maxZoom: 16});
    </script>

Я подозреваю, что мне нужно сообщить листовке, чтобы получить переменную маркера, возможно, в

var geoJsonLayer = L.geoJson(geoJsonData, {
            onEachFeature: function (feature, layer) {
                layer.bindPopup(feature.properties.address);
            }
        });

но я не могу заставить его работать.

я даже пробовал, как было предложено где-то еще:

var geoJsonLayer = L.geoJson(geoJsonData, {
            onEachFeature: function (feature, layer) {
                layer.bindPopup(feature.properties.address),
layer.setIcon(feature.properties.marker);
            }
        });

я все еще получаю сообщение об ошибке: Uncaught TypeError: Object cmIcon не имеет метода createIcon

есть ли у кого-нибудь идеи о том, как это сделать?

Любая помощь будет принята с благодарностью.

Заранее спасибо.


person user2130449    schedule 08.10.2013    source источник


Ответы (1)


Вам нужно сообщить группе MarkerClusterGroup, как создать значок. В документах кластера маркеров показан пример с DivIcon следующим образом:

var markers = new L.MarkerClusterGroup({
    iconCreateFunction: function(cluster) {
        return new L.DivIcon({ html: '<b>' + cluster.getChildCount() + '</b>' });
    }
});

Вместо этого вы можете использовать свой собственный значок, например:

var markers = new L.MarkerClusterGroup({
    iconCreateFunction: function(cluster) {
        // decide which icon you want to use
        return (cluster.getChildCount() > 10) ? cmIcon : otherIcon;
    }
});
person kielni    schedule 10.10.2013