这里我使用JavaScript类加载客户端当前位置的地图。从导航地理位置获取结果但无法将其分配给类属性位置。这是我的班级
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函数。
答案 0 :(得分:0)
更改
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');
}
};
为:
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');
}
};