Django/개인 프로젝트1(안전한 보행길 지도)

Django 지도 라이브러리 Folium Map 이용하기

민돌v 2021. 8. 12. 00:21
728x90

https://thalals.tistory.com/103?category=499919 

 

Django Leaflet.js 지도 라이브러리 불러오기

1. Leaflet.js 라이브러리 호출하기 먼저 head 부분에 leaflat.js css와 js 링크를 추가해, leaflet 라이브러리 사용할 수 있도록 합니다. 2. Map 설정 1) 크기 설정 div의 크기를 설정해준다. 2) map 생성하고 타..

thalals.tistory.com

 

이전 게시물에서 Leaflet 라이브러리를 이용해서 지도를 불러왔는데,

Django는 Python 기반이므로 데이터를 조작하기 더 편한 Folium 오픈소스 라이브러리를 사용하기로 했다.


1. Folium 설치

folium을 이용하기 위해서 먼저 install 해준다

pip install folium

2. Folium Map 설정하기

1) 기본 지도를 만들려면 시작 좌표를 Folium에 전달하기만 하면 된다고 합니다.

구조는 " m = folium.Map(location=[45.5236, -122.6750]) " 가 기본이고 여기서 더 추가할 수 있다.

 

(1) ZommStart

Map(location=[45.5236, -122.6750], zoom_start=13)

(2) tiles set

* folium mapbox 

folium.Map(location=[45.5236, -122.6750],
           tiles='Mapbox',
           API_key='your.API.key')

* folium Leaflet

folium.Map(location=[45.372, -121.6972],
           zoom_start=12,
           tiles='http://{s}.tiles.yourtiles.com/{z}/{x}/{y}.png',
           attr='My Data Attribution')

마지막으로 Folium은 leaflet.js호환되는 모든 사용자 정의 타일셋 전달을 지원한다고 합니다.


실습을 해보자

1. views.py 에서 map 객체를 렌더링해서 html 파일에 보내려하니 이런 에러가 떳다.

error code : folium.folium.Map object at ~

map rendering

2. 알아보니, Folium map 객체를 html에 호출하기위해서는 iframe이 있는 문자열로 반환해야한다고 한다.

쥬피터를 이용할때는 지도를 html로 저장해주어 랜더링한다고 한다. (비슷한 맥락이 아닐까..?)

 

iframe 문자열로 반환.. 하지만 안됨

 

3. 문자열로 반환해도 안되서 찾아보니, Django 탬블릿에 이게 안전하다고 알려줘야한다고 한다.

https://stackoverflow.com/questions/50517620/django-and-folium-integration

 

Django and Folium integration

Django newbie here: my aim is to integrate Folium to an html page. so what I have at the moment: polls/views.py def show_map(request): #creation of map comes here + business logic m = f...

stackoverflow.com

사용자 지정 django 템플릿에 폴륨을 포함하려면 컨텍스트에 추가하기 전에 먼저 그림을 렌더링해야 합니다(그림에 지도의 모든 부분이 반복적으로 로드됨). 템플릿에서 렌더링 함수를 호출하여 그림의 헤더, html 및 스크립트 부분에 개별적으로 액세스해야 합니다. 또한 이러한 부분은 html 삽입을 허용하려면 django 템플릿 태그로 "안전"으로 표시해야 합니다.

{{map | safe }}

 

map safe

 

 

views.py

from django.shortcuts import render
import folium

# Create your views here.
def home(request) :
    map = folium.Map(location=[37.7854, 128.4698],zoom_start=15, width='100%', height='100%',)
    maps=map._repr_html_()  #지도를 템플릿에 삽입하기위해 iframe이 있는 문자열로 반환 

    return render(request,'../templates/home.html',{'map' : maps})

html

초간단..

<body>
    <!-- 전체 지도 -->
    <div id='map'>
        {{map|safe}}
    </div>
</body>

3. Geocoder.ip 로 현재위치 랜더링

첫 화면을 사용자가 보았을때 현재위치부터 시작하고 싶었다.

 

1) Geocoder 오픈소스 라이브러리를 이용

- geocoder를 이용하는 이유는, 최대한 다른 기업에서 제공하는 api는 사용을 지양하려 했으며,

코드를 간결하고 빠르게 짜고싶었다.

- geocoder는 Python으로 구현되어있기도하고 간단하게 install해와서 사용할 수 있을 것 같기에 사용을 해보았다.

 

2) pip install geocoder

3) geocoder 객체 생성

import geocoder

g = geocoder.ip('me')   #현재 내위치

4) folium 객체에 geocoder 객체 정보 파싱

폴리엄 객체 LOCATION 부분에 geocoder객체.lating (좌표)를 매핑

    map = folium.Map(location=g.latlng,zoom_start=15, width='100%', height='100%',)

 

https://github.com/DenisCarriere/geocoder#ip-addresses

 

GitHub - DenisCarriere/geocoder: Python Geocoder

:earth_asia: Python Geocoder. Contribute to DenisCarriere/geocoder development by creating an account on GitHub.

github.com

 

완전히 내 위치는 아니고 서울로 매핑된다.. 흠 이유가 모지?

 


4. Folium Flugin

https://github.com/python-visualization/folium

 

GitHub - python-visualization/folium: Python Data. Leaflet.js Maps.

Python Data. Leaflet.js Maps. . Contribute to python-visualization/folium development by creating an account on GitHub.

github.com

이 이상 유용한 folium flugin 옵션들을 잘 정리해두었기에 마지막으로 보고 마무리 하겠다.

 

참고

GeoCoder 공식문서 : https://geocoder.readthedocs.io/api.html

Folium plug option : https://dailyheumsi.tistory.com/85

folium Quick Starter : https://python-visualization.github.io/folium/quickstart.html#Getting-Started

반응형