How to create a KML file using R

前端 未结 4 1988
梦如初夏
梦如初夏 2021-02-02 16:35

I have written a R script to get some map point data (Latitude and Longitude values). I am able to plot them in R and visualize them. But now I want to generate a KML file from

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-02 17:00

    I think is worth mentioning the plotKML package as well.

    However, for easy sharing among colleagues I found interesting the mapview package based on leaflet package. One can save a map as HTML document with various options for a background map; no need of Google Earth and the HTML map will run on your browser.

    Some examples:

    library(sp)
    library(rgdal)
    library(raster)
    library(plotKML)
    library(mapview)
    
    # A SpatialPointsDataFrame example
    data(meuse)
    coordinates(meuse) <- ~x+y
    proj4string(meuse) <- CRS("+init=epsg:28992") # CRS Amersfoort (Netherlands)
    # make a KML file from SpatialPointsDataFrame object
    # will get a warning like "Reprojecting to +proj=longlat +datum=WGS84 ..."
    # as it is expected to work with geographical coordinates with datum=WGS84, 
    # but seems that it takes care of the reprojecting. 
    plotKML::kml(meuse,
                 file.name    = "meuse_cadium.kml",
                 points_names = meuse$cadmium,
                 colour    = "#FF0000",
                 alpha     = 0.6,
                 size      = 1,
                 shape     = "http://maps.google.com/mapfiles/kml/pal2/icon18.png")
    # Or, an easy to make interactive map with mapView()
    mapView(meuse)
    
    # A RasterLayer example   
    data(meuse.grid)
    gridded(meuse.grid) <- ~x+y
    proj4string(meuse.grid) <- CRS("+init=epsg:28992")
    dist_rst <- raster(meuse.grid["dist"])
    # make a KML file from RasterLayer object
    plotKML::kml(dist_rst,
                 file.name    = "dist_rst.kml",
                 colour_scale = SAGA_pal[[1]])
    # Or, easy to make interactive map with mapView() - display raster and add the points
    mapView(dist_rst, legend=TRUE) + meuse
    # However, note that for bigger raster datasets mapView() might reduce from resolution
    

    More examples with plotKML here, with a tutorial here. For mapview, an intro can be found here.

提交回复
热议问题