中安拓也のブログ

プログラミングについて書くブログ

angular2-google-mapsでジオコーディング

最近仕事でGoogle Map周りを触ることが多いので、下記ライブラリを使って、ジオコーディング処理のデモアプリを作成してみた。

github.com

開発環境
  • Angular@2.4.1
  • angular2-google-maps@0.17.0
  • typescript@2.0.10

ジオコーディングとは

Google Maps API公式サイトによると、住所を地理的座標(緯度、経度)に変換する処理とのこと。

ジオコーディングデモアプリ概要

入力した場所情報をジオコーディングで緯度と経度に変換後、GoogleMapに渡すといった処理をAngularを使って書いている。

GoogleMapで表示したい場所をテキストボックスに入力してEnterすると。。。
f:id:l08084:20161229160340p:plain

GoogleMapの中心が、テキストボックスに入力した地点に移動する。という仕様
f:id:l08084:20161229160450p:plain

デモアプリソースコード解説

angular2-google-mapsの導入方法は、公式サイトのGetting Startedがわかりやすいので割愛する。

  • src/app/app.component.ts
import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { MapService } from '../services/map.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  lat: number = 35.6329007;
  lng: number = 139.8782003;
  zoom: number = 15;

  constructor(
    public mapService: MapService,
  ) {}

  public geocoding(f: NgForm) {
    let self = this;

    this.mapService.geocoding(f.value.address).then(
      rtn => {
        let location = rtn[0].geometry.location;

        self.lat = location.lat();
        self.lng = location.lng();
      }
    );
  }
}

テキストボックスに入力した場所情報を、MapServiceに渡した後、MapServiceからジオコーディング結果として渡された緯度と経度を受け取り、HTML上のGoogleMapに渡している。

  • src/app/app.component.ts
<form #f="ngForm" (ngSubmit)="geocoding(f)" novalidate>
  <input type="text" name="address" placeholder="場所を入力してください...(例:品川駅)" ngModel>
</form>
<sebm-google-map [latitude]="lat" [longitude]="lng" [zoom]="zoom">
  <sebm-google-map-marker [latitude]="lat" [longitude]="lng"></sebm-google-map-marker>
</sebm-google-map>
  • src/services/map.service.ts
import { Injectable } from '@angular/core';

import { MapsAPILoader } from 'angular2-google-maps/core';

declare let google: any;

@Injectable()
export class MapService {
    private geocoder: any = null;

    constructor(
        private mapsAPILoader: MapsAPILoader,
    ) { }

    public geocoding(address: string): Promise<any> {
        return this.mapsAPILoader.load().then(() => {
            this.geocoder = new google.maps.Geocoder();

            return new Promise((resolve, reject) => {
                this.geocoder.geocode({ 'address': address }, (result: any, status: any) => {
                    if (status === google.maps.GeocoderStatus.OK) {
                        resolve(result);
                    } else {
                        reject(status);
                    }
                });
            });
        });
    }

}

・src/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';

import { AgmCoreModule } from 'angular2-google-maps/core';

import { MapService } from '../services/map.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AgmCoreModule.forRoot({
      apiKey: 'YourAPIKey'
    })
  ],
  providers: [
    MapService,
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

mapsAPILoader.load()を使用すると、「google is not undefined〜」的なエラーが発生しないので良いです。

作成したデモアプリは、Githubにあげているので、取得したGoogle mapsのAPIKEYを設定すれば動かすこともできます。

手順
  1. GoogleMapのAPIKEYを取得して、src/app/app.module.tsに設定
  1. npm installコマンド実施
  1. ng serveコマンド実施
  1. ブラウザを開いて、http://localhost:4200/ を入力する


github.com

参考サイト

github.com

mae.chab.in