JS Google Maps API 〜GeoLocation 現在位置の取得〜

Google Maps API

現在位置の取得処理でつまづいたのでメモです。
GoogleMapを作成して、現在位置の取得メソッド(監視メソッド)を使用するときの実装サンプルです。

function getCurrentPos() {
    if (navigator.geolocation == false) {
        console.log("GEO Locaion is unable.");
        return;
    }
    // オプション・オブジェクト
    var optionObj = {
        "enableHighAccuracy": false ,
        "timeout": 5000 ,
        "maximumAge": 0 ,
    };
    target = {
        latitude: 0,
        longitufe: 0
    };
    // Navigator.geolocation
    id = navigator.geolocation.watchPosition(
        successCurrentPos // 成功時のコールバック
        , errorCurrentPos // 失敗時のコールバック
        , optionObj); // オプション設定

}

そして、現在位置を取得してその位置を表示する処理は。はじめは以下のようなコードでした。>はじめは以下のようなコードでした。

/** GeoLocationの成功時のコールバック */
function successCurrentPos(position) {
    var crd  = position.coords;
    // マップの位置情報オブジェクト
    var mapLatLng = new google.maps.LatLng(crd.latitude, crd.longitude);

    if (target.latitude === crd.latitude && target.longitude === crd.longitude) {
      console.log('Congratulations, you reached the target');
      navigator.geolocation.clearWatch(id);
    }
    // マーカーの追加
    var current = new google.maps.Marker({
        map: map,
        position: mapLatLng
    });
    console.log("test");
}

しかし、これだと以下のようなエラーメッセージが出ました。
this.setValues is not a function
「なんでぢゃ〜」と叫びはしませんでしたが、結構手間取りました。そして[こちらのページ](https://stackoverflow.com/questions/36598503/error-this-setvalues-is-not-a-function-in-js-code-use-google-map-api)を参照すると
newが抜けてるよ」というアドバイスがあり。。。
同じようにして修正したら直しました。
そしてついでなので、このままオプションの変更をしない状態だと、毎度おなじみのオーバーレイが表示されるので、そいつを別のものに変更したいと思い以下のようにオプションを設定してやるとできました。

// マーカーの追加
var current = new google.maps.Marker({
    map: map,
    position: mapLatLng,
    icon: './mapImg/you.png' // ファイルの指定
});

![自作アイコンの追加](https://pbs.twimg.com/media/D_bqqRaU8AIAOit.jpg:large)
でわでわ。。。



投稿者:

takunoji

音響、イベント会場設営業界からIT業界へ転身。現在はJava屋としてサラリーマンをやっている。自称ガテン系プログラマー(笑) Javaプログラミングを布教したい、ラスパイとJavaの相性が良いことに気が付く。 Spring framework, Struts, Seaser, Hibernate, Playframework, JavaEE6, JavaEE7などの現場経験あり。 SQL, VBA, PL/SQL, コマンドプロント, Shellなどもやります。

コメントを残す