LoginSignup
0
0

More than 5 years have passed since last update.

Golang / Google Places API Web Serviceの利用

Last updated at Posted at 2016-09-26

はじめに

Google Places API Web Service ををGolangから利用するためのライブラリであるGo Client for Google Maps Services を利用してNearbySearchを実施した(長い)ので備忘録がてら以下に記載します。

ちなみに、Google Places API Web ServiceからのレスポンスはJSON形式であり、上記のライブラリを利用する方法も含めて

  1. "encoding/json"パッケージを利用してJSONレスポンスをパースする
    1. あらかじめ構造体を定義しておく
    2. とりあえずinterface{}で突っ込んで後処理する
  2. JSON形式が簡単に扱える"github.com/bitly/go-simplejson"パッケージを利用してJSONレスポンスをパースする
  3. 公式の "googlemaps.github.io/maps"を利用

をすべて試しましたが当然ながら3.の公式を利用したものが圧倒的にラクでした。というか、最初からちゃんと検索すればよかった。

リソース

そもそものAPI仕様と公式ライブラリについての情報
- Places API Web Service/Place Search仕様
- googlemaps.github.io/mapsのReference Documentation

実行環境

Mac OS X: 10.11.4, Go: 1.7

事前準備

"googlemaps.github.io/maps"

prettyはレスポンス結果表示用、contextは実行時引数に必要になります。

$ go get googlemaps.github.io/maps
$ go get github.com/kr/pretty
$ go get golang.org/x/net/context

コード

サンプルコードはDirectionなのでこれを修正したものを作成。

package main

import (
    "log"

    "github.com/kr/pretty"
    "golang.org/x/net/context"
    "googlemaps.github.io/maps"
)

func main() {
    c, err := maps.NewClient(maps.WithAPIKey("<自分のAPIキー>"))
    if err != nil {
        log.Fatalf("fatal error: %s", err)
    }
    r := &maps.NearbySearchRequest{
        Location: &maps.LatLng{Lat: <緯度>, Lng: <経度>},
        Radius:   <検索する半経>,
    }
    resp, err := c.NearbySearch(context.Background(), r)
    if err != nil {
        log.Fatalf("fatal error: %s", err)
    }

    pretty.Println(resp)
}

実行結果

$ go run main.go
maps.PlacesSearchResponse{
    Results: {
        {
            FormattedAddress: "",
            Geometry:         maps.AddressGeometry{
                Location:     maps.LatLng{Lat:35.7090259, Lng:139.7319925},
                LocationType: "",
                Viewport:     maps.LatLngBounds{
                    NorthEast: maps.LatLng{Lat:35.8175167, Lng:139.9198565},
                    SouthWest: maps.LatLng{Lat:35.5208632, Lng:139.5629047},
...
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0