谷歌地图无法为类属性分配导航器位置

google map unable assign navigator position to class property

本文关键字:分配 导航 位置 属性 谷歌地图      更新时间:2023-09-26

这里我使用一个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函数

变化

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');
    }
};