0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

google-maps-services-jsにてGeocoding APIがiOSで動作しない場合の対応

Last updated at Posted at 2019-12-12

背景

事故マップというサービスを個人開発で最近始めました。

スクリーンショット 2019-12-12 23.31.11.png

マップを任意の場所にジャンプさせるために検索フォーム設けています。

ここでユーザーが入力したキーワードをGoogleMaps Geocoding APIにかけて
そのキーワードに対応する緯度経度を取得してMapを移動させるようにしています。

また、このGeocoding APIを利用するためにGoogle謹製のgoogle-maps-services-jsを使っていました。

遭遇した問題

実際のコードではこのような感じでリクエストを処理していました。

Vue.js
const googleMapsClient = require("@google/maps").createClient({
  key: "API key XXXXXXXX",
  Promise: Promise
});


findLatLng() {
  googleMapsClient
    .geocode({
      address: this.searchWord // ユーザーが入力したキーワード
    })
    .asPromise()
    .then((response) => {
      console.log(response.json.results);
    })
    .catch(err => {
      console.log(err);
    });
}

macOS、Androidでは上記コードでレスポンスを取得する事ができていたのですが、
何故かiOSだけ次のようなエラーが出て必ず処理が失敗してしまいました。

TypeError: Request header field User-Agent is not allowed by Access-Control-Allow-Headers.

原因

いろいろ調べてみましたが、正確な原因はわかりませんでした。

しかし、別のモジュールを使ってみたところうまくいったので
google-maps-services-jsの何らかの不具合の可能性が高いです。

対応

実際、vue2-geocoderを使ったところ、iOSでもレスポンスを取得できるようになりました。

ちなみにvue2-geocoderは中でXMLHttpRequestを使ってリクエストを投げているだけの非常にシンプルな作りになっています。

vue2-geocoderでの処理例

Vue.js
findLatLng(evt) {
    evt.preventDefault()

    var self = this
    var addressObj = { address_line_1: this.searchWord }
    Vue.$geocoder.send(addressObj, response => {
        console.log(response)

        if (response.status == 'ZERO_RESULTS') {
             console.log("no result");
        } else {
             console.log(response.results[0]);
        }
    })
}
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?