Leaflet is one of the most popular open-source JavaScript libraries for interactive maps.
There are many ways to visualize latitude and longitude data on map using R, such as using ggmaps or RgoogleMaps packages. But these packages generate static maps images only. Leaflet allow users to zoom in or zoom out in a very interactive way.
In this post we will learn how to create a interactive map using Leaflet in R & also we will learn how to map and style - latitude and longitude data using R & Leaflet package!
Here leaflet() initializes the leaflet workspace & addTiles() will bring default OpenStreetMap tiles. OpenStreetMap is a free open-source service to create a free editable map of the world.
It allow users to zoom in or zoom out in a very interactive way.
library(leaflet)
map = leaflet() %>%
addTiles()
map
setView() basically sets the center of the map view and the zoom level;
map = leaflet() %>%
addTiles() %>%
setView(lng = 77.231 , lat =28.612, zoom = 12)
map
Suppose we have to Mark 28.61293 N, 72.229564 E India Gate coordinates on Map.
my_map = leaflet() %>%
addTiles() %>%
addMarkers(
lat=28.612923,
lng =77.229564,
popup="<b>India Gate</b><br>
<a href='https://en.wikipedia.org/wiki/India_Gate'>India Gate Wiki</a>")
my_map
Creating sample data of latitude & longitide, after that setting data in AddMarkers
Data <- data.frame(
place = c("Delhi","Gurugram","Noida","Faridbad","GrNoida"),
lat = c("28.63","28.4644","28.56","28.418","28.491"),
lon = c("77.231","77.026","77.38","77.31","77.5226"))
my_map = leaflet() %>%
addTiles() %>%
setView(lng = 77.231 , lat =28.63, zoom = 9)%>%
addMarkers(
lat=Data$lat,
lng =Data$lon,
popup=Data$place)
my_map
Suppose we have to show an image as marker. Here we have india flag.
IndiaFlag <- makeIcon(
iconUrl = "http://shobhitsingh.in/images/IN.png",
iconWidth = 60, iconHeight = 40
)
my_map = leaflet() %>%
addTiles() %>%
setView(lng = 77.22298 , lat =28.612899, zoom = 9)%>%
addMarkers(
lat=28.612846,
lng =77.231122,
icon = IndiaFlag,
popup="India Gate")
my_map
Suppose we have to show an Color Cirle Markers as marker.
green <- data.frame(
lat = c("28.63","28.4644","28.56","28.418","28.491"),
lon = c("77.231","77.026","77.38","77.31","77.5226"))
yellow <- data.frame(
lat = c("28.64","28.5644","28.46","28.428","28.291"),
lon = c("77.331","77.126","77.138","77.131","77.1226"))
map <- leaflet() %>%
addTiles() %>%
setView(lng = 77.22298 , lat =28.512899, zoom = 10)%>%
addCircleMarkers(data=green,lat= ~ green$lat, lng = ~ green$lon, radius = 10, color = '#008000', popup = "Green")%>%
addCircleMarkers(data=yellow,lat= ~ yellow$lat, lng = ~ yellow$lon, radius = 10, color = '#ffff00', popup = "Yellow")
map
For more details, please visit these Link
Thanks!
Happy Learning! Your feedback would be appreciated!