Javascript google map无法将导航器位置分配给类属性
在这里,我使用一个JavaScript类来加载客户端当前位置的映射。正在从导航地理位置获取结果,但无法将其分配给类属性位置。这是我的班级Javascript google map无法将导航器位置分配给类属性,javascript,google-maps,google-maps-api-3,Javascript,Google Maps,Google Maps Api 3,在这里,我使用一个JavaScript类来加载客户端当前位置的映射。正在从导航地理位置获取结果,但无法将其分配给类属性位置。这是我的班级 var GoogleMaps = function(mapID){ var Self = this; var config = {}; this.mapID = mapID; this.geocoder = null; this.mapOptions = null; this.map = null; th
var GoogleMaps = function(mapID){
var Self = this;
var config = {};
this.mapID = mapID;
this.geocoder = null;
this.mapOptions = null;
this.map = null;
this.infowindow = null;
this.marker = null;
this.useCurrent = false;
this.position = null;
this.latlng = null;
this.init = function(userCurrent){
this.useCurrent = userCurrent;
this.geocoder = new google.maps.Geocoder();
this.mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
};
this.infowindow = new google.maps.InfoWindow();
this.map = new google.maps.Map(document.getElementById(this.mapID),this.mapOptions);
this.map.setTilt(45);
if(this.useCurrent){
this.getPosition();
this.setPosition();
}
};
this.getPosition = function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
var currentPosition = position;
console.log(currentPosition);//Working perfect
this.position = position; // Not working
});
} else {
error('Geo Location is not supported');
}
};
this.setPosition = function(){
//console.log('%c '+this.position,"background:orange");
this.latlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
};
this.loadMap = function(){
this.map.setCenter(this.latlng);
this.map.setTilt(45);
this.map.setZoom(2);
};
}
var Map = new GoogleMaps("map_canvas");
$(window).load(function(){
Map.init(true);
Map.loadMap();
});
签出类中的getPosition函数。更改
if(this.useCurrent){
this.getPosition();
this.setPosition();
}
及
致:
及
这是以什么方式进行的。位置=位置;不工作?如果有错误,那是什么??它仍然是空的吗?它被分配了错误的值?当我将位置记录到控制台时,得到了完美的值,但是当分配给位置对象时,它仍然是空的。所以问题是getPosition中的地理位置请求是异步的。当您随后立即调用setPosition时,您正在试图在getPosition函数完成之前引用this.position;不是函数this.setPosition=函数{?TypeError:this.setPosition不是函数this.setPosition;正在尝试使用setPosition为当前位置的google地图设置默认latlng
this.getPosition = function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
var currentPosition = position;
console.log(currentPosition);//Working perfect
this.position = position; // Not working
});
} else {
error('Geo Location is not supported');
}
};
if(this.useCurrent){
this.getPosition();
}
this.getPosition = function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
var currentPosition = position;
console.log(currentPosition);//Working perfect
this.position = position;
this.setPosition();
});
} else {
error('Geo Location is not supported');
}
};