tmap转leaflet后添加leaflet功能报错:Invalid map parameter咨询
Let's break down why you're hitting that error and how to fix it step by step:
1. First, Fix the Obvious Typo
Looking at your code, you defined your spatial data as battle_dat, but then used tm_shape(dat) to create the tmap. That's a simple typo—dat doesn't exist, which might be causing unexpected behavior before you even convert to leaflet. Change that line to:
tm <- tm_shape(battle_dat) + tm_dots(col="duration") # make tmap
2. Ensure You're Loading All Required Packages
The addDrawToolbar() function comes from the leaflet.extras package, not the core leaflet package. If you haven't loaded it, that could lead to dispatch issues. Make sure you have these packages loaded at the top of your script:
library(tmap) library(leaflet) library(leaflet.extras) library(dplyr) library(sp)
3. Verify the Map Object Type & Compatibility
When you use tmap_leaflet(tm), it returns a standard leaflet map object, but sometimes version mismatches between tmap and leaflet can cause weird dispatch errors. Here's a cleaned-up, tested version of your code that should work:
# Load data and preprocess battle_dat <- read.csv("GeoBattleData_YZ.csv") battle_dat <- battle_dat %>% select(war, atkr, defr, date, long, lat, dist_att, dist_def, duration) %>% mutate(year = substr(date, 1, 4)) %>% filter(!is.na(long)) # Using dplyr's filter instead of base subsetting for clarity # Convert to SpatialPointsDataFrame battle_dat <- SpatialPointsDataFrame( coords = battle_dat[, c("long", "lat")], data = battle_dat, proj4string = CRS("+init=EPSG:4326") ) # Create tmap and convert to leaflet tm_map <- tm_shape(battle_dat) + tm_dots(col = "duration") leaflet_map <- tmap_leaflet(tm_map) # Add draw toolbar correctly leaflet_map %>% addDrawToolbar( targetGroup = 'draw', polylineOptions = FALSE, markerOptions = FALSE, circleOptions = TRUE, polygonOptions = FALSE, singleFeature = TRUE, circleMarkerOptions = FALSE )
Why Your Original Code Might Have Failed
- The typo in
tm_shape(dat)could have created an invalid tmap object, which when converted to leaflet, became an unrecognizable object for the draw toolbar function. - Missing the
leaflet.extraspackage means R might be trying to use a non-existent function, leading to the dispatch error you saw. - Using base subsetting (
battle_dat[!is.na(battle_dat$long),]) works, but switching todplyr::filtermakes the code more readable and avoids potential issues with spatial objects.
Bonus: Mixing tmap & Leaflet Best Practices
You're right that tmap shines for quick, polished static/interactive maps, while leaflet gives you granular control over interactive features. A good workflow is:
- Use tmap to set up your base layers (points, polygons, styles) quickly.
- Convert to leaflet, then add specialized interactive features (like draw tools, custom popups, or plugins) using leaflet and leaflet.extras functions.
内容的提问来源于stack exchange,提问作者dkro

