まず病院検索サイトから札幌市北区の内科の住所をスクレイピング
library(plyr)
library(dplyr)
library(rvest)
#### お医者さんガイドから持ってきた北区内科のサンプルデータ
h_name <- html("http://www.10man-doc.co.jp/static/hokkaido/0020.html") %>%
html_nodes(xpath = '//*[@class="h_name"]/a') %>%
html_text()
h_name %>% head
## [1] "諸岡内科クリニック" "札幌複十字総合健診センター"
## [3] "北海道大野病院附属駅前クリニック" "小林内科小児科医院"
## [5] "中江病院" "北20条内科クリニック"
h_address <- html("http://www.10man-doc.co.jp/static/hokkaido/0020.html") %>%
html_nodes(xpath = '//*[@class="address"]') %>%
html_text()
h_address %>% head
## [1] "札幌市北区北八条西4-1-1 パストラルビルN8 1F"
## [2] "札幌市北区北八条西3-28 札幌エルプラザ5F"
## [3] "札幌市北区北八条西3-28 札幌エルプラザビル6F"
## [4] "札幌市北区北二十八条西5-2-16 "
## [5] "札幌市北区北二十二条西7-2-1 "
## [6] "札幌市北区北二十条西6-2-10 "
偉い先生の関数でgeocodingしちゃいます。
library(RCurl)
library(rjson)
# teramonagiさんの便利な関数使わせてもらいました
# http://d.hatena.ne.jp/teramonagi/20121029/1351507308
# 住所を文字列で入力すると位置情報をjson形式で返却する関数
GetLocationInformation <-function(address)
{
#URL用にエンコーディング
address <- RCurl::curlEscape(address)
#URL(API)生成
url <- paste("http://maps.googleapis.com/maps/api/geocode/json?address=",
address,"&sensor=false®ion=JP&language=ja",sep="")
RCurl::getURL(url)
}
#住所(文字列ベクトル)を緯度・経度へ
GetLatitudeAndLongitude <- function(addresses)
{
#各住所をgoogle APIで位置情報(json)へ
jsons <- sapply(addresses,GetLocationInformation)
#googleAPIで取得した位置情報(json)から経度・緯度情報を抽出
ExtractLatitudeAndLongitude <- function(json)
{
latitude <- rjson::fromJSON(json)$results[[1]]$geometry$location$lat
longitude <- rjson::fromJSON(json)$results[[1]]$geometry$location$lng
c(lat=latitude,lon=longitude)
}
t(sapply(jsons,ExtractLatitudeAndLongitude))
}
#緯度経度情報へ変換
location <- GetLatitudeAndLongitude(h_address)
location <- as.data.frame(location)
location <-cbind(location,h_name)
colnames(location)[1:2] <-c("latitude","longitude")
location <- location[,c(2,1,3)]
location %>% head
## longitude latitude
## 札幌市北区北八条西4-1-1 パストラルビルN8 1F 141.3493 43.07059
## 札幌市北区北八条西3-28 札幌エルプラザ5F 141.3499 43.07072
## 札幌市北区北八条西3-28 札幌エルプラザビル6F 141.3499 43.07101
## 札幌市北区北二十八条西5-2-16 141.3405 43.09523
## 札幌市北区北二十二条西7-2-1 141.3399 43.08787
## 札幌市北区北二十条西6-2-10 141.3420 43.08487
## h_name
## 札幌市北区北八条西4-1-1 パストラルビルN8 1F 諸岡内科クリニック
## 札幌市北区北八条西3-28 札幌エルプラザ5F 札幌複十字総合健診センター
## 札幌市北区北八条西3-28 札幌エルプラザビル6F 北海道大野病院附属駅前クリニック
## 札幌市北区北二十八条西5-2-16 小林内科小児科医院
## 札幌市北区北二十二条西7-2-1 中江病院
## 札幌市北区北二十条西6-2-10 北20条内科クリニック
いよいよleaflet package。
ベースの地図決めて、マーカーにポップアップ付けて、地図の位置と、倍率決めたら あっという間にプロットできます。
詳しいことは下記サイトで https://rstudio.github.io/leaflet/
library(leaflet)
m = leaflet(location) %>% addProviderTiles("CartoDB.Positron")
m %>%
addMarkers(data = location, lat = ~ latitude, lng = ~ longitude, popup = location$h_name) %>%
setView(median(location[,"longitude"]),median(location[,"latitude"]),zoom=14)