1

I have a class to handle geoinformation and google maps services:

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}

My Import:

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

Now in my Script (Vue.js) I call this class-method getLocationFromGeoData:

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

Except in getCoordinatesFromGeoData I get undefinedwhen I try to access my coordinates object.

Do I have to take care of something special when returning values from imported classes?

Brotzka
  • 2,959
  • 4
  • 35
  • 56
  • can you rename your class like `export class MapService` and try? – Aravind S Jul 09 '18 at 07:00
  • 2
    `navigator.geolocation.getCurrentPosition` is asyncrhonous ... – Jaromanda X Jul 09 '18 at 07:01
  • `getCoordinatesFromGeoData` has no return statement of its own. – Quentin Jul 09 '18 at 07:02
  • @Quentin the return statement is there ;) Is there a way to maka a function "wait" for the response of ``navigator.geolocation.getCurrentPosition``? – Brotzka Jul 09 '18 at 07:08
  • Now it's working. I've used a Promise described [here](https://scotch.io/tutorials/javascript-promises-for-dummies). My ``getLocationFromGeoData`` now returns a Promise which is handled in my VusJS-Object. – Brotzka Jul 09 '18 at 07:27

0 Answers0