Skip to content

Instantly share code, notes, and snippets.

@allieus
Last active February 15, 2020 13:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save allieus/29ed3e8b4d425b3bb731b538ac02e0fe to your computer and use it in GitHub Desktop.
Save allieus/29ed3e8b4d425b3bb731b538ac02e0fe to your computer and use it in GitHub Desktop.
네이버 지도 v3, 장고 위젯 예시

네이버 지도 v3 지도, 장고 Point 위젯

from django import forms
from django.core.validators import RegexValidator
from .widgets import NaverMapPointWidget
class PostForm(forms.Form):
point = forms.CharField(validators=[RegexValidator(r'^[+-]?[\d\.]+,[+-]?[\d\.]+$')], widget=NaverMapPointWidget)
<script type="text/javascript" src="https://openapi.map.naver.com/openapi/v3/maps.js?clientId={{ naver_client_id }}"></script>
<style>
#naver_map_point_{{ id }} {
width: {{ width }};
height: {{ height }};
}
</style>
<div id="naver_map_point_{{ id }}"></div>
<script>
(function() {
var base_point = new naver.maps.LatLng({{ base_lat }}, {{ base_lng }});
var map = new naver.maps.Map(document.getElementById('naver_map_point_{{ id }}'), {
center: base_point
});
var marker = new naver.maps.Marker({
position: base_point,
map: map
});
naver.maps.Event.addListener(map, 'click', function(e) {
marker.setPosition(e.coord);
document.getElementById('{{ id }}').value = e.coord.lng() + ',' + e.coord.lat();
});
})();
</script>
# 중략
NAVER_CLIENT_ID = '' # FIXME: https://developers.naver.com/register?defaultScope=map 를 통해 발급
import re
from django import forms
from django.conf import settings
from django.template.loader import render_to_string
class NaverMapPointWidget(forms.TextInput):
def render(self, name, value, attrs=None):
if not attrs: attrs = {}
attrs['readonly'] = 'readonly'
width = str(self.attrs.get('width', 800))
height = str(self.attrs.get('height', 600))
if width.isdigit():
width += 'px'
if height.isdigit():
height += 'px'
context = dict(attrs, **self.attrs)
# default point : 강남역
context['base_lat'] = '37.497921'
context['base_lng'] = '127.027636'
context['naver_client_id'] = settings.NAVER_CLIENT_ID
context['width'] = width
context['height'] = height
if value:
try:
lng, lat = re.findall(r'[+-]?[\d\.]+', value)
context['base_lat'] = lat
context['base_lng'] = lng
except (IndexError, ValueError):
pass
rendered = super(NaverMapPointWidget, self).render(name, value, attrs)
html = render_to_string('naver_map_point_widget.html', context)
return rendered + html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment