티스토리 뷰

0. 개발 환경

$ ionic -v
6.1.0

$ node -v
v12.16.0

$ npm -v
6.13.4

$ cordova -v
9.0.0 (cordova-lib@9.0.1)

ionic version 4이상부터는 아래 방식이 적용 가능한 것으로 보인다.

 

1. ionic 프로젝트 생성

$ ionic start 프로젝트명 blank

 

2. package 설치

$ ionic cordova plugin add cordova-plugin-geolocation
$ npm install --save @ionic-native/geolocation

 

3. Geolocation 사용하기

import { Geolocation } from '@ionic-native/geolocation/ngx';

...

@NgModule ({
	...
	providers: [
    	...
        Geolocation,
        ...
    ],
	...
})
export class AppModule{}

 

4. Google Map Api Key 얻기

  (1) https://developers.google.com/maps/documentation/javascript/get-api-key

 

Get an API Key  |  Maps JavaScript API  |  Google Developers

New Users: To use Google Maps Platform, you need a project with a billing account and at least one Google Maps Platform API or SDK enabled. Visit Get Started with Google Maps Platform for full instructions or click the button below if you are new to the pl

developers.google.com

  (2) Google Cloud Platform 접속 후 프로젝트가 없다면 생성한다.

  (3) 프로젝트 생성 후 Maps Javascript API "사용 설정" 을 눌러 사용할 수 있게 한다.

  (4) 다음 안내를 따라 "사용자 인증 정보"에서 "+ 사용자 인증 정보 만들기"로 API Key를 생성한다.

  (5) index.html에 다음 코드를 추가한다.

<!-- Google Map Api Key -->
  <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"
          type="text/javascript"></script>

YOUR_API_KEY 부분을 위에서 생성한 본인의 API Key로 변경한다.

 

5. 현재 위치의 위/경도 출력하기

import {Component, OnInit} from '@angular/core';

import { Geolocation } from '@ionic-native/geolocation/ngx';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit{

  constructor(private geolocation: Geolocation) {}

  ngOnInit(): void {
    this.loadMap();
  }

  async loadMap() {
    const rta = await this.geolocation.getCurrentPosition(); // 현재 위치 정보 얻기
    const myLatLng = {
      lat: rta.coords.latitude,
      lng: rta.coords.longitude
    };
    console.log(myLatLng); // 콘솔 창에 현재 위치의 위/경도 표시
  }

}

ionic의 geolocation package에서 제공하는 getCurrentPosition() 함수를 사용하여 현재 위치의 정보를 얻을 수 있다.

 

6. 지도 표시하기

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Google Map Api
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <div id="map"></div>
</ion-content>

home.page.html 파일에 id가 map인 div를 추가한다.

...

declare var google;

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit{
  ...
  async loadMap() {
    ...
    console.log(myLatLng);

    const mapEle: HTMLElement = document.getElementById('map');
    const map = new google.maps.Map(mapEle, {
      center: myLatLng, // 지도의 중앙값 설정
      zoom: 12          // 지도의 zoom 정도 설정
    });
  }
}

home.page.ts에 id가 map인 요소를 찾아 해당 요소에 지도 객체를 만든다.

#map {
  width: 100%;
  height: 100%;
}

지도가 전체 화면에 보일 수 있도록 home.page.scss를 수정한다. 

 

7. 현재 위치에 마크 그리기 및 코드 정리

import {Component, OnInit} from '@angular/core';
import { LoadingController } from '@ionic/angular';

import { Geolocation } from '@ionic-native/geolocation/ngx';

declare var google;

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit{

  mapRef = null;

  constructor(private loadingController: LoadingController,
              private geolocation: Geolocation) {}

  ngOnInit(): void {
    this.loadMap();
  }

  async loadMap() {
    const loading = await this.loadingController.create();
    loading.present();


    const myLatLng = await this.getLocation();

    // id가 map인 요소 찾기
    const mapEle: HTMLElement = document.getElementById('map');
    // 지도 객체 생성
    this.mapRef = new google.maps.Map(mapEle, {
      center: myLatLng, // 지도의 중심 설정
      zoom: 12          // 지도의 zoom 설정
    });

    // map이 로딩되고 초기에 한번 수행되는 이벤트
    google.maps.event.addListenerOnce(this.mapRef, 'idle', () => {
      loading.dismiss();
      this.addMarker(myLatLng.lat, myLatLng.lng); // 마크 표시하기
    });
  }

  // 현재 위치 위/경도에 마크 표시하기
  private addMarker(lat: number, lng: number) {
    const marker = new google.maps.Marker({
      position: { lat, lng },
      zoom: 8,
      map: this.mapRef,
      title: 'Mark my location!'
    });
  }

  // 현재 위치 정보 가져와서 위/경도 반환하기
  private async getLocation() {
    const rta = await this.geolocation.getCurrentPosition();
    return {
      lat: rta.coords.latitude,
      lng: rta.coords.longitude
    };
  }

}

현재 위치에 마크를 표시할 있도록 코드를 추가하고 기존 코드를 보기 좋게 수정하였다.

 

8. 결과

지도에 마크 표시하기

 

 

위 내용에 대한 전체 결과 코드는 github에서 확인할 수 있다.

 

https://github.com/hanbee1005/ionic_geolocation

 

hanbee1005/ionic_geolocation

Contribute to hanbee1005/ionic_geolocation development by creating an account on GitHub.

github.com

 

'ionic' 카테고리의 다른 글

ionic 개발 - HTTP 통신하기  (0) 2020.06.02
ionic 개발 - QR Code Scan  (0) 2020.06.01
ionic 개발 - Local Storage 사용하기  (0) 2020.05.27
ionic 개발 기초 매뉴얼  (0) 2020.05.13
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함