2014-04-29 131 views
0

我想設置一個變量來保存緯度和經度變量在Google地圖上繪圖(我試圖讓它在稍後添加到集合中)。我正在運行控制檯長時間測試,發現我的函數中的變量是設置座標。我將如何能夠這樣做? (對不起,我還是新的JavaScript和Backbone.js的)骨幹Js - 設置地理位置變量[未定義變量]

var Area = Backbone.View.extend({ 
    el: '#load', 

    initialize: function(){ 
     //this.getLocation(); 
     this.canvasId = 'map'; 
     this.area = '<h2>Area of BAC</h2><div id="'+this.canvasId+'"></div>'; 
    }, 

    render: function(){ 
     this.$el.html(this.area); 
     this.getLocation(); 
     console.log(this.lat+' '+this.lng+' - Confirmed'); 
     //this.createMap(this.lat, this.lng); 
     //google.maps.event.addDomListener(window, 'load', this.createMap); 

    }, 

    createMap: function(lat, lng){ 
     //var mlat = lat; 
     //var mlong = lng; 
     //alert(lat+' '+lng); 
     var mapOptions = { 
      center: new google.maps.LatLng(40.7430473, -74.1777488), 
      //center: new google.maps.LatLng(mlat, mlng), 
      zoom: 15 
     } 
     var map = new google.maps.Map(document.getElementById(this.canvasId), mapOptions); 
    }, 

    getLocation: function(){ 
     console.log('Test - getGeolocation'); 
     if(navigator.geolocation){ 
      //navigator.geolocation.getCurrentPosition(this.setLatLng); 
      navigator.geolocation.getCurrentPosition(this.setLatLng); 
     }else{ 
      alert('Either you have no internet connection or your browser is not supported'); 
     } 
    }, 

    setLatLng: function(position){ 
     console.log('Test - setLatLng'); 
     this.lat = position.coords.latitude; 
     console.log('Test - setLatLng-lat'); 
     this.lng = position.coords.longitude; 
     console.log('Test - setLatLng-lng'); 
     console.log(this.lat+' '+this.lng); 
    }, 

    throwErr: function(){ 
     alert('Cannot get coords'); 
    } 

}); 

我的控制檯日誌:

Test - getGeolocation Area.js:32 
undefined undefined - Confirmed Area.js:13 
Test - setLatLng Area.js:42 
Test - setLatLng-lat Area.js:44 
Test - setLatLng-lng Area.js:46 
19.7180872 -89.0860836 

回答

0

猜測:這個問題似乎是與this參考。

更新getLocation方法如下:

getLocation: function(){ 
    var self = this; 
    console.log('Test - getGeolocation'); 
    if(navigator.geolocation){ 
     //navigator.geolocation.getCurrentPosition(this.setLatLng); 
     navigator.geolocation.getCurrentPosition(function (position) { 
      self.setLatLng(position); 
     }); 
    }else{ 
     alert('Either you have no internet connection or your browser is not supported'); 
    } 
},