Drag and Change Marker Color MapboxJS

by Aryo Pinandito

HTML

<link rel="stylesheet" href="https://api.mapbox.com/mapbox.js/v3.0.1/mapbox.css">
<script src="https://api.mapbox.com/mapbox.js/v3.0.1/mapbox.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<html>

  <body>
    <div id="map"></div>
  </body>

</html>

CSS

#map {
  width: 100%;
  height: 500px;
}

JavaScript

$(function() {
  L.mapbox.accessToken = 'put your public access token here';
  var map = L.mapbox.map('map', 'mapbox.streets')
    .setView([-7.9690694, 112.632992], 16);
  var circleMarker;
  var redIcon = L.mapbox.marker.icon({
    'marker-size': 'small',
    'marker-symbol': 'circle',
    'marker-color': '#f00'
  });
  map.on('click', function(e) {
    $('#info').html("Lat, Lon : " + e.latlng.lat + ", " + e.latlng.lng);
    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;
    circleMarker.on('dragstart', function(e) {
      originLatLng = circleMarker.getLatLng();
      console.log(originLatLng);
    });
    circleMarker.on('dragend', function(e) {
      if (originLatLng.lat == circleMarker.getLatLng().lat) console.log('true');
      else console.log('false');
    });
    circleMarker.on('click', function(e) {
      console.log(e);
      this.setIcon(redIcon);
    });
  });

});