本文小编为大家详细介绍“leaflet高级交互特性怎么用”,内容详细,步骤清晰,细节处理妥当,希望这篇“leaflet高级交互特性怎么用”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
成都创新互联公司主要从事成都网站设计、网站建设、网页设计、企业做网站、公司建网站等业务。立足成都服务博山,十载网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18982081108
在制作高质量在线数据地图的项目中,leaflet结合扩展的HTML性能,可以呈现非常人性化的动态效果,如能结合css、shiny等装饰器和交互框架,几乎可以胜任常见的动态交互网站的制作。
library("sp")
library("leaflet")
options(stringsAsFactors = FALSE,check.names = FALSE)
锁定目录:
setwd("D:/R/mapdata/State")
导入美国地图素材(含数据)
states<-geojsonio::geojson_read("us-states.geojson", what = "sp")
一个简单的开始:(引用mapbox地图)
m <- leaflet(states) %>%
setView(-96, 37.8, 4) %>% #设置呈现的视觉中心
addProviderTiles("MapBox", options = providerTileOptions(
id = "mapbox.light", #添加地图图层
accessToken = Sys.getenv('MAPBOX_ACCESS_TOKEN')))
m %>% addPolygons() #地图呈现
#分箱及设置色盘:
bins <- c(0, 10, 20, 50, 100, 200, 500, 1000, Inf)
pal <- colorBin("YlOrRd", domain = states$density, bins = bins)
m %>% addPolygons(
fillColor = ~pal(density), #显式声明颜色映射变量
weight = 2, #线宽
opacity = 1, #透明度
color = "white", #颜色
dashArray = "3",
fillOpacity = 0.7) #填充透明度
m %>% addPolygons(
fillColor = ~pal(density),
weight = 2,
opacity = 1,
color = "white",
dashArray = "3",
fillOpacity = 0.7,
highlight = highlightOptions( #设置高亮属性
weight = 5,
color = "#666",
dashArray = "",
fillOpacity = 0.7,
bringToFront = TRUE))
#设置鼠标点击事件:
labels <- sprintf("%s
%g people / mi2",states$name,states$density) %>% lapply(htmltools::HTML) #转化为HTML格式标签
m <-m %>% addPolygons(
fillColor = ~pal(density),
weight = 2,
opacity = 1,
color = "white",
dashArray = "3",
fillOpacity = 0.7,
highlight = highlightOptions(
weight = 5,
color = "#666",
dashArray = "",
fillOpacity = 0.7,
bringToFront = TRUE
),
label = labels,
labelOptions = labelOptions( #标签选项设置(参数类别HTML属性)
style=list("font-weight"="normal",padding="3px 8px"),
textsize="15px",
direction="auto")
);m
#增加图例:
m %>% addLegend(pal = pal, values = ~density, opacity = 0.7, title = NULL,
position = "bottomright")
以下是该案例的完整代码:
# From http://leafletjs.com/examples/choropleth/us-states.js
(数据源,js格式记得保存为geojson格式)
bins <- c(0, 10, 20, 50, 100, 200, 500, 1000, Inf)
pal <- colorBin("YlOrRd", domain = states$density, bins = bins)
labels <- sprintf(
"%s
%g people / mi2",states$name, states$density
) %>% lapply(htmltools::HTML)
leaflet(states) %>%
setView(-96, 37.8, 4) %>%
addProviderTiles("MapBox", options = providerTileOptions(
id = "mapbox.light",
accessToken = Sys.getenv('MAPBOX_ACCESS_TOKEN'))) %>%
addPolygons(
fillColor = ~pal(density),
weight = 2,
opacity = 1,
color = "white",
dashArray = "3",
fillOpacity = 0.7,
highlight = highlightOptions(
weight = 5,
color = "#666",
dashArray = "",
fillOpacity = 0.7,
bringToFront = TRUE),
label = labels,
labelOptions = labelOptions(
style = list("font-weight" = "normal", padding = "3px 8px"),
textsize = "15px",
direction = "auto")) %>%
addLegend(pal = pal, values = ~density, opacity = 0.7, title = NULL,
position = "bottomright")
读到这里,这篇“leaflet高级交互特性怎么用”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注创新互联行业资讯频道。