简体   繁体   中英

get value from function in exported function JS

today I'm working on a project in JavaScript. I've an exported function A that is in an other file then my location.js. When I click I get the location of an user.

But how do I get the values from a function in an exported function?

I need the coordinates in the function.

Code:

if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                function(position) {
                    lat = position.coords.latitude;
                    long = position.coords.longitude;
                    coordinates = {
                        latitude: lat,
                        longitude: long
                    };
                    console.log(JSON.stringify(coordinates));
                    return coordinates;
                }, {
                   (errorHandling)
                }};

Could someone help me out?

Thanks for advance!

navigator.geolocation.getCurrentPosition is an async function which works on callback principle and not promises.

In order to get the returned values, you either need to convert it into a promise based function or pass a callback function to it which you call when data is available like

const getLocation = (callback) => {
    ....

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            function myLocation(position) {
                lat = position.coords.latitude;
                long = position.coords.longitude;
                callback({
                    latitude: lat,
                    longitude: long
                }); // the callback method
            },
            function(error) {
                ...
            }
        );
    } 
    ...
};

module.exports = { getLocation };

Now you can call the function and set the coordinates in state of react like

import Button from './button.js';

import { getLocation } from './functions/getLocation.js';

class Card extends React.Component {
    state = {
       coordinates: {}
    }
    getLocationCoordinates = () => {
        getLocation((coordinates) => {
            this.setState({coordinates})
        })
    }
    render() {
        const { lat, lng } = this.state.coordinates;
        return (
            <div id={'location'} className={'card'}>
                    ...
                    <Button function={this.getLocationCoordinates} text={'Allow Location'} />
                    ...
            </div>
        );
    }
}

export default Card;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM