乐趣区

Leaflet-for-R添加带数字的Marker

效果

代码

x <- c(116.493195,
       116.473195,
       116.453195,
       116.493195,
       116.473195,
       116.453195,
       116.493195,
       116.473195,
       116.453195
       )

y <- c(39.993253,
       39.993253,
       39.993253,
       39.973253,
       39.973253,
       39.973253,
       39.953253,
       39.953253,
       39.953253
       )

color_vector <- c('#642100', 
              '#DC143C', 
              '#FF1493',
              '#FF1493',
              '#FF00FF',
              '#800080',
              '#4B0082',
              '#0000CD',
              '#405af5',
              '#1E90FF'
              )

position_df <- data.frame(x=x,y=y)


library(leaflet)

leaflet() %>%
  addTiles('http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
    options=tileOptions(tileSize=256, minZoom=3, maxZoom=20, subdomains="1234"),
    attribution = '&copy; <a href="http://ditu.amap.com/"> 高德地图 </a>',
    group="高德地图" 
  ) %>% 
  onRender(
    "
    function(el, x, data) {console.log('debug', el, x, data);
      var color = data['color'];
      var pos_x = data['pos']['x'];
      var pos_y = data['pos']['y'];
      
      var markers = [];
      for(var i=0; i<pos_x.length; i++) {var marker = L.marker([pos_y[i], pos_x[i]], {
          icon: L.divIcon({
            className: 'my-custom-icon',
            html: '' + (i + 1)
          })
        });
        marker.addTo(this);
        marker.getElement().style.minWidth = '16px';
        marker.getElement().style.minHeight = '16px';
        marker.getElement().style.lineHeight = '20px';
        marker.getElement().style.background = '' + color[ i % 10];
        marker.getElement().style.borderRadius = '50%';
        marker.getElement().style.marginLeft = '-8px';
        marker.getElement().style.marginTop = '-8px';
        marker.getElement().style.textAlign = 'center';
        marker.getElement().style.color = '#fff';
        marker.getElement().style.fontSize = '12px';
        markers.push(marker);
      }
      console.log(markers.length);
      // this.fitBounds(L.featureGroup(markers).getBounds()); // not work...
    }
    ", data=list(pos=position_df, color=color_vector)
  ) %>%
  fitBounds(min(position_df$x), min(position_df$y), max(position_df$x), max(position_df$y))
退出移动版