2015年9月12日土曜日

[javascript][geolocation] ややハマりマジコスメ

あ、プログラマっぽい職種に就職しました。
ありがとうございます。

で、ブラウザで、javascirpt でも位置情報取得できるじゃないですか。
navigator.geolocation.getCurrentPoition(succ,err,opt);
みたいなやつ、

あれ、結果返ってくるまでに時間かかりますので、気をつけて下さい。
調子こいてオブジェクト化して楽して使いまわせるようにしようとか思って、


  1. var GPS = function(){
  2.  this.curr();
  3. }
  4. _GPS = GPS.prototype;
  5. _GPS.geo = navigator.geolocation;
  6. _GPS.lat  = 0; // latitude
  7. _GPS.lng  =0; // longitude
  8. _GPS.time = 0 // time
  9. _GPS.e = false // error -> true;
  10. _GPS.opt = {
      enableHighAccuracy : true,
      timeout            : 5000,
      maximumAge         : 0
  11. };
  12. _GPS.getTime = function(){
  13.  this.time= (new Date()).getTime();
  14. }
  15. _GPS.succ = function(pos){
     var co = pos.coords;
  16.  _GPS.lat = co.latitude;
  17.  _GPS.lng = co.longitude;
     _GPS.getTime();
    }
  18. _GPS.err = function(e){
     _GPS.e = true;
     _GPS.lat = -1;
     _GPS.lng = -1;
     _GPS.getTime();
  19. }

  20. _GPS.curr = function(){
  21.  var _t = this;
     _t.geo.getCurrentPosition(_t.succ,_t.err,_t.opt);
  22. }

とかだと、

var gps = new GPS();
alert(gps.lat); => 0

で、はぁ?ってなります。

なので、

  1. var GPS = function(){
  2.  this.curr();
  3. }
  4. _GPS = GPS.prototype;
  5. _GPS.geo = navigator.geolocation;
  6. _GPS.lat  = 0; // latitude
  7. _GPS.lng  =0; // longitude
  8. _GPS.time = 0 // time
  9. _GPS.e = false // error -> true; 
  10. _GPS.get = false // got location -> true
  11. _GPS.opt = {
      enableHighAccuracy : true,
      timeout            : 5000,
      maximumAge         : 0
  12. };
  13. _GPS.getTime = function(){
  14.  this.time= (new Date()).getTime();
  15. }
  16. _GPS.succ = function(pos){
     var co = pos.coords;
  17.  _GPS.lat = co.latitude;
  18.  _GPS.lng = co.longitude;
     _GPS.getTime();
  19.  _GPS.get = true;
    }
  20. _GPS.err = function(e){
     _GPS.e = true;
     _GPS.lat = -1;
     _GPS.lng = -1;
     _GPS.getTime();
  21.  _GPS.get = true;
  22. }

  23. _GPS.curr = function(){
  24.  var _t = this;
     _t.geo.getCurrentPosition(_t.succ,_t.err,_t.opt);
  25. }

で、
var gps = new GPS();

var loop = setInterval(function(){
 if(gps.get){
  alert(gps.lat + " - " + gps.lng);
  clearInterval(loop);
 }
},500);

とかみたいにしなきゃダメっすね。
まぁ、結論としては、普通に書いた方がいいって感じ。
どうしてもグローバルにいろいろ書きたくないんじゃーって人は、
こんな感じになるんでしょうかね。
あと、success の function の中が深くなるのが嫌な人とかかな?

まぁ、そんな感じで。

0 件のコメント:

コメントを投稿