구글 맵 API 사용 준비
- 구글에 로그인하고 구글 맵 플랫폼 사이트로 이동합니다. https://cloud.google.com/maps-platform/
- 사이트 내의
시작하기
버튼을 누르세요. 그러면 GCP(Google Cloude Platform) 무료 평가판 이용을 위한 절차가 진행됩니다.
- (2단계) 결제수단 등록까지 완료하면 90일 동안 Google Cloud Platform에서 제공하는 기능들을 300$ 내에 무료로 이용할 수 있습니다. 구글 안내에 따르면 평가판이 지나도 자동으로 결제되지는 않는다고 합니다.
- 간단한 설문이 진행됩니다. 본인이 사용하고자하는 목적에 맞게 설문하시면 됩니다. 설문 내용에 따라 기능을 추천해준다고 합니다.
- 설문이 끝나면 API 키를 받습니다.
My First Project
라는 이름으로 첫 번째 프로젝트가 생성되었을 겁니다. 해당 프로젝트의 결제 계정을 처음 만들었던 결제 계정으로 설정합니다. 결제 계정을 설정하지 않으면 API를 사용할 수 없습니다.
제품 및 리소스 검색
에서google maps platform
을 검색합니다.
Maps JavaScript API
를 사용합니다.
cafedetail에 구글맵 추가하기
- 구글 맵을 보여줄 cafedetail.html 에 다음 코드를 추가합니다.
[사용자 키]
부분에 본인이 발급받은 API 키를 추가합니다.
<script> function initMap() { var jeju = {lat: 33.3616658, lng: 126.5204118}; var map = new google.maps.Map(document.getElementById('map'), { zoom: 10, center: jeju }); var marker = new google.maps.Marker({ position: {lat: {{cafe.lat}}, lng: {{cafe.lng}}}, map: map }); } </script>
<body>
태그 마지막 부분에 다음 코드를 추가합니다.<script async defer src="https://maps.googleapis.com/maps/api/js?key=[사용자 키]&callback=initMap"> </script>
- 해당 페이지로 가면 이제 구글맵을 볼 수 있습니다.
구글맵에 마커 추가하기
구글 맵에는 개발자가 원하는 위치를 가리키는 마커를 삽입할 수 있습니다. 해당 카페의 위치를 마커로 표시해보겠습니다.
마커를 삽입하기 위해서는 해당 위치의 위도와 경도를 알아야 합니다. Cafe 모델에 카페의 위도와 경도를 저장하는
lat
, lng
필드를 정의합니다.from django.db import models class Cafe(models.Model): name = models.CharField(max_length=50) locations = [ ('Hangyeong-myeon', '한경면'), ('Hallim-eup', '한림읍'), ('Aewol-eup', '애월읍'), ('Jeju-si', '제주시'), ('Jocheon-eup', '조천읍'), ('Gujwa-eup', '구좌읍'), ('Daejeong-eup', '대정읍'), ('Andeok-myeon', '안덕면'), ('Seogwipo-si', '서귀포시'), ('Namwon-eup', '남원읍'), ('Pyoseon-myeon', '표선면'), ('Seongsan-eup', '성산읍'), ('Udo-myeon', '우도면'), ] location = models.CharField(max_length=50, choices=locations) lat = models.FloatField(null=True) lng = models.FloatField(null=True) mainphoto = models.ImageField(blank=True, null=True) subphoto = models.ImageField(blank=True, null=True) published_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) content = models.TextField() phone = models.CharField(max_length=20, null=True) insta = models.CharField(max_length=20, null=True) def __str__(self): return self.name
models.py
파일을 수정하면 makemigrtions
와 migrate
를 해야 한다는 사실 잊지 않으셨죠?(myvenv)root@goorm:/workspace/컨테이너명/mysite# python manage.py makemigrations Migrations for 'main': main/migrations/0005_auto_20200720_0806.py - Add field lat to cafe - Add field lng to cafe (myvenv)root@goorm:/workspace/컨테이너명/mysite# python manage.py migrate ... Running migrations: Applying_main.0005_auto_20200720_0806... OK
샘플로 구글맵에서 각 지역을 대표하는 장소를 검색하여 좌표를 알아낸 다음 아래와 같이 입력합니다. (구글 맵에서 마우스 우클릭하여 알아낼 수 있습니다.)
1번 카페- (33.4619638, 126.3273297) - 애월읍사무소
2번 카페 - (33.6628574, 126.0112614)- 제주시청
3번 카페 - (33.5380993, 126.631991) – 조천읍사무소
이제 구글 맵 API 코드에
marker
를 추가합니다.<script> function initMap() { var jeju = {lat: 33.3616658, lng: 126.5204118}; var map = new google.maps.Map(document.getElementById('map'), { zoom: 10, center: jeju }); var marker = new google.maps.Marker({ position: {lat: {{cafe.lat}}, lng: {{cafe.lng}}}, map: map }); } </script>
그러면 이제 지도에 해당 위도와 경도에 마커가 표시됩니다.
API 키 보안 설정
API 키는 노출 될 시 다른 이용자에게 악용될 수 있기 때문에 노출되더라도 안전하도록 사전에 막아 둘 필요가 있습니다.
- Google Maps Platform에서
사용자 인증 정보
로 들어가 발급 받은 키를 클릭하여 설정으로 들어갑니다.
- HTTP 리퍼러 설정을 통해 본인이 원하는 사이트, 즉 본인이 개발한 사이트에서만 사용할 수 있도록 해당 도메인을 리퍼러로 등록합니다.
-
API 제한사항
에서 해당 키가 사용되길 원하는 API를 제한합니다. 우리는Maps JavaScript API
만 사용할 것이기 때문에 이것만 허용하도록 설정합니다.
- 설정을 저장하면 제한사항이 잘 추가된 것을 목록에서 확인할 수 있습니다.
이제 다른 사이트에서 API를 사용할 시 해당 사이트는 허용되지 않았다는 의미의 에러 메시지가 노출 됩니다. (실제 반영은 최대 5분 소요될 수 있습니다.)
google map에 대하여 좀 더 알고 싶으시다면 아래 튜토리얼을 참고하세요.