R | Leaflet | 인터랙티브 지도(1) - Markers

2023. 2. 13. 15:08·R/leaflet

 

 

 

 

R의 대표적인 인터랙티브 지도는 Plotly 패키지를 사용해 구현할 수 있다. 

이외에도 Leaflet 패키지를 사용해 인터랙티브 지도를 구현할 수 있는데, 

 

생각보다 사용 방법이 잘 안 나와 있어서 포스팅을 통해서 Leaflet 사용법을 설명할 것이다. 

 

이번 포스팅에서는 leaflet 패키지로 Marker를 사용해 위치 정보를 지도 위에 나타낼 것이다. 

 

 

leaflet_markers.html
5.49MB


 

00. 패키지 로드 및 데이터 불러오기 

 

1) 패키지 로드 

## 패키지 로드 
library(dplyr)
library(leaflet)

### 한글 폰트 설정 
library(showtext)
font_add_google("Nanum Gothic", "nanumgothic")

 

2) 소상공인시장진흥공단_상가(상권)정보

 

: 영업 중인 전국 상가업소 데이터를 제공
(상호명, 업종코드, 업종명, 지번주소, 도로명주소, 경도, 위도 등)

https://www.data.go.kr/data/15083033/fileData.do

 

소상공인시장진흥공단_상가(상권)정보_20221231

영업 중인 전국 상가업소 데이터를 제공합니다.<br/>(상호명, 업종코드, 업종명, 지번주소, 도로명주소, 경도, 위도 등)

www.data.go.kr

data.file <- read.csv("", fileEncoding = "utf-8")
data.raw<- data.file
data.raw %>% head()


data.cafe <- data.raw %>% filter(상권업종소분류명=='커피전문점/카페/다방')
data.cafe %>% head()

 

 

3) shape 파일 불러오기: 시도

시도 shape file - http://www.gisdeveloper.co.kr/?p=2332 

 

대한민국 최신 행정구역(SHP) 다운로드 – GIS Developer

 

www.gisdeveloper.co.kr

 

library(rgdal)

### read shape file
shp <- rgdal::readOGR(".shp")

### 좌표 확인: UTM-K(GRS-80) 좌표계에서 WGS84 경위도 좌표계로 변환
from.crs <- "+proj=tmerc +lat_0=38 +lon_0=127.5 +k=0.9996 +x_0=1000000 +y_0=2000000 +ellps=GRS80 +units=m +no_defs"
to.crs <- "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"
shp <- spTransform(shp, to.crs) # 좌표계가 올바르게 변함

 

 

4)  KOSIS에서 제공하는 행정구역(시군구) 별, 성별 인구수 데이터

https://kosis.kr/statHtml/statHtml.do?orgId=101&tblId=DT_1B040A3 

 

KOSIS

 

kosis.kr

data.pop <- read.csv(".csv")
data.pop

 

 

 

 


 

01. 기본 지도 불러오기 

 

- leaflet을 사용해서 기본 지도를 불러오려면  leaflet() 함수, addTiles() 함수 setView() 함수가 필요하다. 

- setView의 lng = "경도", lat = "위도"에 중심 좌표를 입력하고,  zoom을 사용하여 원하는 위치의 지도를 불러올 수 있다. 

leaflet() %>%
  addTiles() %>% 
  setView(lng=, lat=, zoom=)

 

1) 대한민국 지도 불러오기 

 

- 지도의 종류는 addProviderTiles(providers$ ) 속성을 사용해서 바꿀 수 있다. 

 

 

- OpenStreetMap

leaflet() %>%
  addProviderTiles(providers$OpenStreetMap) %>% 
  setView(lng=127.381653, lat=36.3523647, zoom=6)

 

 

- CartoDB

 

leaflet() %>%
  addProviderTiles(providers$CartoDB) %>% 
  setView(lng=127.381653, lat=36.3523647, zoom=6)

 

 

지도 종류는 많은 데 되는 건 별로 없다... 그래도 위의 2개의 지도를 제일 많이 사용하게 됨.

 


02. Circle Markers  - 커피전문점 위치 지도 위에 표현 

 

1) addCircleMarkers() 

- 소상공인시장진흥공단_상가(상권) 정보 대전에서 커피전문점만 추출하여 지도 위에 표현 

- addCircleMarkers() 함수를 사용

leaflet(data=data.cafe) %>% 
   setView(lng=127.381653, lat=36.3523647, zoom=11) %>% 
   addTiles() %>% 
   addCircleMarkers(lng=~경도, lat=~위도)

 

 

 

2) radius, stroke,  fillOpacity 설정

- radius으로 원의 반경을 설정할 수 있다. 

leaflet(data=data.cafe) %>% 
   setView(lng=127.381653, lat=36.3523647, zoom=11) %>% 
   addTiles() %>% 
   addCircleMarkers(lng=~경도, lat=~위도,
                    radius = 2)

 

 

- stroke = False로 설정하면 원의 테두리를 없앨 수 있다. 

leaflet(data=data.cafe) %>% 
   setView(lng=127.381653, lat=36.3523647, zoom=11) %>% 
   addTiles() %>% 
   addCircleMarkers(lng=~경도, lat=~위도,
                    stroke = F)

 

 

- fillOpacity = n(0~1)를 설정하여 원 안의 투명도를 설정할 수 있다. 

leaflet(data=data.cafe) %>% 
   setView(lng=127.381653, lat=36.3523647, zoom=11) %>% 
   addTiles() %>% 
   addCircleMarkers(lng=~경도, lat=~위도,
                    stroke = F,
                    fillOpacity = n)

 

좌 : fillOpacity = 1 /  우 : fillOpacity = 0.2

 

 

 

3) color 설정 

 

- color = "컬러코드"로 설정하면 모든 circle의 색이 바뀐다. 

leaflet(data=data.cafe) %>% 
   setView(lng=127.381653, lat=36.3523647, zoom=11) %>% 
   addTiles() %>% 
   addCircleMarkers(lng=~경도, lat=~위도,
                    radius = 2,
                    color = "#FF00FF")

 

 

 

- 자치구별(범주형)로 색상 달리 지정(대전광역시 5개 자치구)

- colorFactor()  함수를 사용하면 범주형 변수의 그룹별로 색상을 지정할 수 있다. 

colorFactor(palette, # 그룹의 수 만큼 c() 함수로 컬러코드를 지정하거나 컬러팔레트를 지정하면 됨.
            domain, # 범주형 변수
            levels = NULL, 
            ordered = FALSE,
            na.color = "#808080", # 값이 na일 경우 색 지정
            alpha = FALSE, 
            reverse = FALSE)

 

 

pal <- colorFactor("YlOrRd", domain = data.cafe$시군구명)
pal


leaflet(data=data.cafe) %>% 
   setView(lng=127.381653, lat=36.3523647, zoom=11) %>% 
   addTiles() %>% 
   addCircleMarkers(lng=~경도, lat=~위도,
                    radius = 2,
                    color = ~pal(시군구명))

  

 

 


 

03. Icon Markers  - 마커를 통해 정보 표시

 

- plotly 패키지의 hover처럼 leaflet 패키지에서도 addMarkers() 함수의 label, popup 속성을 사용해 정보를 나타낼 수 있다. 

- label은 마우스 커서를 마커 위에 올려놨을 때, 뜨는 정보를 지정할 수 있고,

  popup을 지정하고 마커를 클릭하면 말풍선처럼 나타난다. 

 

1) 대전광역시 서구의 커피전문점 위치 

leaflet(data=data.cafe %>% filter(시군구명 =="서구")) %>% 
   setView(lng=127.381653, lat=36.3523647, zoom=14) %>% 
   addTiles() %>%  
   addMarkers(lng=~경도, lat=~위도,
              label=~상호명,
              popup=~paste(상호명, "<BR>", 도로명주소,sep=""))

 

왼쪽: label / 오른쪽 : popup

 

 

 

2) 그룹화 - clusterOptions=markerClusterOptions()

 

- 위의 지도처럼 표시할 마커의 개수가 많은 경우 clusterOptions=markerClusterOptions()을 사용해서 인접한 마커끼리 그룹화를 할 수 있다. 

leaflet(data=data.cafe) %>% 
   setView(lng=127.381653, lat=36.3523647, zoom=14) %>% 
   addTiles() %>%  
   addMarkers(lng=~경도, lat=~위도,
              label=~상호명,
              popup=~paste(상호명, "<BR>", 도로명주소,sep=""),
              clusterOptions = markerClusterOptions())

 

 

 

3)  사용자 지정 마커

 

- icons() 함수를 사용하여 사용자가 마커를 직정 원하는 디자인으로 설정할 수 있다. 

- 커피잔 png 출처: https://www.flaticon.com/free-icons/coffee 

Icons_coffee <- icons(iconUrl = "C://coffee.png", # png가 저장되어 있는 경로나 url을 입력
  iconWidth = 20, iconHeight = 20,
  iconAnchorX = 25, iconAnchorY = 30)


leaflet(data=data.cafe) %>% 
   setView(lng=127.381653, lat=36.3523647, zoom=14) %>% 
   addTiles() %>%  
   addMarkers(lng=~경도, lat=~위도,
              icon = Icons_coffee, # icon속성에 사용자 지정 마크 
              label=~상호명,
              popup=~paste(상호명, "<BR>", 도로명주소,sep=""),
              clusterOptions = markerClusterOptions())

 

 


 

04. Awesome Icons

 

- Leaflet 패키지에서는 더 다양한 마커 아이콘을 지원한다. 

https://github.com/lennardv2/Leaflet.awesome-markers

 

GitHub - lennardv2/Leaflet.awesome-markers: Colorful, iconic & retina-proof markers for Leaflet, based on the Font Awesome/Twitt

Colorful, iconic & retina-proof markers for Leaflet, based on the Font Awesome/Twitter Bootstrap icons. - GitHub - lennardv2/Leaflet.awesome-markers: Colorful, iconic & retina-proof markers...

github.com

- addAwesomeMarkers() 함수를 사용하면 여러 가지 커스텀 마커를 사용할 수 있고, 사용 방법은 addMarkers() 함수와 동일하다. 

 

1)  대전광역시 자치구별로 색상 지정 

getColor <- function(data.cafe) {
  sapply(data.cafe$시군구명, function(시군구명) {
  if(시군구명 == "대덕구") {
    "green"
  } else if(시군구명 == "동구") {
    "orange"
  } else if(시군구명 == "서구") {
    "blue"
  }
     else if(시군구명 == "유성구") {
    "yellow"
  }
     else if (시군구명 == "중구"){"red" }
     })
   }

 

 

2) awesomeIcons() 함수를 사용하여 아이콘 커스텀  

## 함수 디폴트 값들
awesomeIcons(icon = "home", 
             library = "glyphicon",
             markerColor = "blue", 
             iconColor = "white", 
             spin = FALSE,
             extraClasses = NULL, 
             squareMarker = FALSE,
             iconRotate = 0,
             fontFamily = "monospace",
             text = NULL)

- icon을 'ios-close'로 지정하고 markerColor를 위에서 만든 함수를 사용해 지정한다. 

icons <- awesomeIcons(
                        icon = 'ios-close',
                        iconColor = 'black',
                        library = 'ion',
                        markerColor = getColor(data.cafe) %>% as.vector())
icons %>% head(20)

 

 

3) 지도 시각화 

 

- addAwesomeMarkers() 함수 안에 위에서 설정한 icons을 icon 속성에 매핑한다. 

leaflet(data=data.cafe) %>% 
   setView(lng=127.381653, lat=36.3523647, zoom=14) %>% 
   addTiles() %>%  
   addAwesomeMarkers(lng=~경도, lat=~위도,
                     icon = icons,
                     label=~상호명,
                     popup=~paste(상호명, "<BR>", 도로명주소,sep=""),
                     clusterOptions = markerClusterOptions())

 

 

 

 

 

 


참고 문헌(reference)

더보기

참고 사이트 

http://rstudio.github.io/leaflet/markers.html

 

Leaflet for R - Markers

Markers Use markers to call out points on the map. Marker locations are expressed in latitude/longitude coordinates, and can either appear as icons or as circles. Data sources Point data for markers can come from a variety of sources: SpatialPoints or Spat

rstudio.github.io

https://leafletjs.com/examples.html

 

Tutorials - Leaflet - a JavaScript library for interactive maps

Leaflet Tutorials Every tutorial here comes with step-by-step code explanation and is easy enough even for beginner JavaScript developers. A simple step-by-step guide that will quickly get you started with Leaflet basics, including setting up a Leaflet map

leafletjs.com

 

 

 

'R > leaflet' 카테고리의 다른 글

R | Leaflet | 인터랙티브 지도(2) - polygon  (0) 2023.02.15
'R/leaflet' 카테고리의 다른 글
  • R | Leaflet | 인터랙티브 지도(2) - polygon
갬보리
갬보리
제발 코드정리좀 하자 (R, SQL, SAS, Python , etc...)
  • 갬보리
    보딩코
    갬보리
  • 전체
    오늘
    어제
    • 분류 전체보기 (49)
      • R (32)
        • dplyr (7)
        • preprocessing (2)
        • EDA (0)
        • ggplot2 (10)
        • plotly (11)
        • leaflet (2)
      • SQL (15)
      • SAS (0)
      • Python (1)
        • preprocessing (0)
        • ML (0)
        • Library (0)
      • ETC (1)
  • hELLO· Designed By정상우.v4.10.3
갬보리
R | Leaflet | 인터랙티브 지도(1) - Markers
상단으로

티스토리툴바