我正在尝试设置一个变量来保存要在谷歌地图上绘制的纬度和经度变量(我稍后会尝试设置它,以便稍后添加到集合中)。我正在运行控制台长测试,发现我的函数中的变量正在设置坐标。我怎么能这么做?(对不起,我还是JavaScript和Backbone.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
猜测:问题似乎出在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');
}
},