首页 > 解决方案 > JavaScript ES6 返回 undefined 虽然已设置

问题描述

我有一门课来处理地理信息和谷歌地图服务:

class MapService {

    constructor(apiKey) {
        this.apiKey = apiKey;
        this.googleMapsClient = require('@google/maps').createClient({
            key: this.apiKey
        });
    }

    getLocationFromGeoData(){
        this.coords = this.getCoordinatesFromGeoData();
        console.log(this.coords); // => undefined
        return this.coords;
    }

    getCoordinatesFromGeoData(){
        if(navigator.geolocation){
            navigator.geolocation.getCurrentPosition(function(position){
                let coords = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };
                console.log(coords); // shows object with coordinates
                return coords;
            })
        } else {
            console.warn("Geolocation wird nicht unterstützt!");
        }
    }
}

export {MapService}

我的导入:

import {MapService} from './modules/MapServices';
let googleMapsApiKey = document.head.querySelector('meta[name="google-maps-api-key"]');
window.MapService = new MapService(googleMapsApiKey.content);

现在在我的脚本(Vue.js)中,我称之为类方法getLocationFromGeoData

var coords = MapService.getLocationFromGeoData();
console.log(coords); // => undefined

除了当getCoordinatesFromGeoDataundefined尝试访问我的坐标对象时得到的。

从导入的类返回值时,我是否需要处理一些特殊的事情?

标签: javascript

解决方案


推荐阅读