1
votes

There are two relevant examples on mapbox's documentation:
Change Marker Color on Click and Draggable Marker

But they go about creating the markers in very different ways.

Method A:
In the "Change Marker Color on Click" example...
they create markers from a geoJSON object, they add a featureLayer to the map and use setGeoJSON to apply that geoJSON object to the featureLayer.

Method B:
In the "Draggable Marker" example...
they create a new marker object via L.marker and then add it to the map with marker.addTo(map)


In Method A I cannot seem to figure out where to add a draggable value within the geoJSON object... or if that is even possible.

In Method B I cannot seem to figure out how to change the marker color after it has been created. There is no initial geoJSON object to iterate through like in the "Change Marker Color on Click" example. However I have found that I can iterate through layers via map.featureLayer.eachLayer and I can successfully see the pins I've created... I just don't see any 'marker-color' property or similar that I can change to affect the markers' color.

Any help would be appreciated... Thanks!

1

1 Answers

1
votes

This question has been asked for more than two years ago, and I don't know whether my answer is still relevant to the question asked. I hope the answer help anybody who faces the same problem as I am.

In the following code I uses mapbox.js v3.0.1 located JS and CSS in https://api.mapbox.com/mapbox.js/v3.0.1/mapbox.js and https://api.mapbox.com/mapbox.js/v3.0.1/mapbox.css respectively

The map object was initialized using the following code:

var map = L.mapbox.map('map', 'mapbox.streets')
    .setView([-7.9, 112.6], 16);

Then I initializes red colored marker into redIcon object using the following code:

var redIcon = L.mapbox.marker.icon({
    'marker-size': 'small',
    'marker-symbol': 'circle',
    'marker-color': '#f00'
});

In map 'click' method use the following code:

var circleMarker;
map.on('click', function(e) {

    circleMarker =
        L.marker([e.latlng.lat, e.latlng.lng],
            {icon: L.mapbox.marker.icon({
            'marker-size': 'small',
            'marker-symbol': 'circle',
            'marker-color': '#fa0'
            }),
            draggable: true
        }).addTo(map);

    var originLatLng;

    // listen to the marker dragstart event
    circleMarker.on('dragstart', function (e) {
        originLatLng = circleMarker.getLatLng();
        console.log(originLatLng);
    });

    // listen to the marker dragend event
    circleMarker.on('dragend', function (e) {
        console.log(circleMarker.getLatLng());
    });

    // listen to the marker click event
    circleMarker.on('click', function(e){
        console.log(e);
        this.setIcon(redIcon);
    });
});

Please see the following JSFiddle to see it in action. Don't forget to change the access token with your Mapbox public access token in the Javascript section.

Thanks and hope this helps.