GeoJson / Mapbox标记:让用户通过按钮[EDITED]更改其属性(例如颜色)

时间:2014-01-06 09:34:13

标签: javascript markers geojson mapbox

(编辑:我收到了一些大拇指因为不小心用未完成的名字发布了这个问题,请不要被吓倒)

如同https://www.mapbox.com/mapbox.js/example/v1.0.0/change-marker-color-click/的示例一样,我试图让用户更改标记的属性(在此示例中为颜色)。

在Mapbox的这个示例中,当用户单击标记时,标记的属性会发生变化。但是,当用户点击html中的一个div(按钮)时,我想更改标记的属性。因此,当用户点击Button1时,Marker 1的颜色应该改变,当用户点击Button2时,Marker 2的颜色应该改变。

您可以在此处找到我的测试HTML:http://weareguide.com/test.html

非常感谢任何帮助。

<!--I would like these buttons to do the job-->
<div class='buttons'>
    <div id='Button1' onclick='AddToSelection(1)'>Change color Marker 1</div> <!--call a function that changes Marker 1-->
    <div id='Button2' onclick='AddToSelection(2)'>Change color Marker 2</div> <!--call a function that changes Marker 2-->
</div>

<div id='map'></div>

<script>
var map = L.mapbox.map('map', 'njit.map-cval12af');

var geoJson = [
    {type:'Feature',geometry:{type:'Point',coordinates:[174.7665232,-36.853447]},properties:{title:"Marker 1",'marker-color':'#4c96ce','marker-size':'small'}},
    {type:'Feature',geometry:{type:'Point',coordinates:[174.7774598,-41.29007064]},properties:{title:"Marker 2",'marker-color':'#4c96ce','marker-size':'small'}}
];

map.markerLayer.setGeoJSON(geoJson);

//This is the current function used in the Mapbox example, I want to replace this with the new function
map.markerLayer.on('click',function(e) {
    e.layer.feature.properties['marker-color'] = '#000000';
    map.markerLayer.setGeoJSON(geoJson);
});
</script>

1 个答案:

答案 0 :(得分:1)

像这样使用..这是一个有效的例子。

<div class='buttons' style="z-index: 100; position: absolute;">
    <input type="button" onclick='AddToSelection(1)' value="Change color Marker 1" /><!--call a function that changes Marker 1-->
    <input type="button" onclick='AddToSelection(2)' value="Change color Marker 2" /> <!--call a function that changes Marker 2-->
</div>

<div id='map'></div>

<script>
  var map = L.mapbox.map('map', 'njit.map-cval12af');

  var geoJson = [
   {type:'Feature',geometry:{type:'Point',coordinates:[174.7665232,-36.853447]},properties:{title:"Marker 1",'marker-color':'#4c96ce','marker-size':'small'}},
   {type:'Feature',geometry:{type:'Point',coordinates:[174.7774598,-41.29007064]},properties:{title:"Marker 2",'marker-color':'#4c96ce','marker-size':'small'}}
  ];

  map.markerLayer.setGeoJSON(geoJson);

  function AddToSelection(mydata) {
      map.markerLayer.eachLayer(function(marker) {
          var feature = marker.feature;
          if(feature.properties['title'] == 'Marker '+mydata) {
              feature.properties['marker-color'] = '#000000';
              map.markerLayer.setGeoJSON(geoJson);
          }
      }
  }      
</script>