Search code examples
javascriptextjsgeolocationopenweathermap

Ext JS: How to pass geolocation values to url?


I'm using Njdhv's ExtJS-GeoLocation library. On the sample usage he defined a function which prints current geolocation values;

//'MyApp.view.dash.DashController' where function defined.

  refreshGeoLocation : function( refresh ) {
            var className = '',
                geo;
            if (Ext.isClassic) {
                className = 'MyApp.utils.OoGeolocation';
            } else if (Ext.isModern) {
                className = 'Ext.util.Geolocation';
            }
            if (className) {
                geo = Ext.create(className, {
                    autoUpdate: false,
                    listeners: {
                        locationupdate: function (geo) {
                            console.log(geo);
                            console.log('Wait for it! Geolocation info is coming up!');
                            Ext.Msg.alert('Success', `New latitude: ${geo.getLatitude()} <br>New Longitude: ${geo.getLongitude()}`);
                            console.log(`New latitude: ${geo.getLatitude()} New Longitude: ${geo.getLongitude()}`);
                        },
                        locationerror: function (geo, bTimeout, bPermissionDenied, bLocationUnavailable, message) {
                            if (bTimeout) {
                                Ext.Msg.alert('Erroe', 'Timeout occurred.');
                            } else {
                                Ext.Msg.alert('Erroe', 'Error occurred');
                            }
                        }
                    }
                });
                geo.updateLocation();
            } else {
                Ext.Msg.alert('Erroe', 'No class found');
            }
        }

How can I be able to pass those printed values in proxy url to LATITUDE and LONGITUDE ?

Ext.define('MyApp.view.dash.WeatherData', {
    extend: 'Ext.DataView',
    xtype: 'weatherData',

    requires: [
        'Ext.data.reader.Json',
        'MyApp.utils.OoGeolocation', //The library using for Geolocation
        'MyApp.view.dash.DashController' //Where refreshGeolocation function defined
    ],

    baseCls: 'weather-panel',
    border: false,

    store: {
        fields: [
            {
                name: 'summary',
                mapping: 'weather[0].main'
            },
            {
                name: 'description',
                mapping: 'weather[0].description'
            }
        ],
        proxy: {
            type: 'jsonp',
            // url: 'http://api.openweathermap.org/data/2.5/weather?lat=36.90&lon=36.64&units=metric&appid=9b59049894d42af608baf69f869b9ace',
            url: 'http://api.openweathermap.org/data/2.5/weather?lat=' + LATITUDE +'&lon=' + LONGITUDE +'&units=metric&appid=9b5904989',
            reader: {
                type: 'json'
            }
        },
        autoLoad: true
    },

    itemTpl: '<div class="weather-image-container"><img src="../../../resources/img/ico_cloud.png" alt="{summary}"/></div>' +
                '<div class="weather-details-container">' +
                '<div>{main.temp}&#176;</div>' +
                '<div>{summary}</div>' +
                '<div>{description}</div>' +
             '</div>'
});

UPDATE! Dear @Njdhv here is updated snippets;

Singleton class

Ext.define("MyApp.view.weather.WeatherUtil", {
    singleton: true,
    alternateClassName: 'weatherutil',
    config: {
        latitude: 0,
        longitude: 0
    },
    constructor: function (config) {
        this.initConfig(config);
    }
});

and DataView class

Ext.define('MyApp.view.weather.WeatherData', {
    extend: 'Ext.DataView',
    xtype: 'weatherdata',

    requires: [
        'Ext.data.reader.Json',
        'MyApp.utils.OoGeolocation', //Geolocation Library
        'MyApp.view.dash.WeatherUtil' //Singleton class
    ],
    ...
    proxy: {
            type: 'jsonp',
            url: `http://api.openweathermap.org/data/2.5/weather?lat=${weatherutil.getLatitude()}&lon=${weatherutil.getLongitude()}&units=metric&appid=9b590`,
            reader: {
                type: 'json'
            }
        },

here is DashController for function through button;

refreshGeoLocation: function (button) {
        var store = button.up('#weatherView').down('weatherdata').getStore();

        store.load({
            url: `http://api.openweathermap.org/data/2.5/weather?lat=${weatherutil.getLatitude()}&lon=${weatherutil.getLongitude()}&units=metric&appid=9b59049894d42af608baf69f869b9ace`,
        });
        button.setDisabled(false);
    },

    getGeolocation : function( refresh ) {
        var className = '',
            geo;
        if (Ext.isClassic) {
            className = 'MyApp.utils.OoGeolocation';
        } else if (Ext.isModern) {
            className = 'Ext.util.Geolocation';
        }
        if (className) {
            geo = Ext.create(className, {
                autoUpdate: false,
                listeners: {
                    locationupdate: function (geo) {
                        console.log(geo);
                        console.log('Wait for it! Geolocation info is coming up!');
                        //Ext.Msg.alert('Success', `New latitude: ${geo.getLatitude()} <br>New Longitude: ${geo.getLongitude()}`);
                        console.log(`New latitude: ${geo.getLatitude()} New Longitude: ${geo.getLongitude()}`);
                    },
                    locationerror: function (geo, bTimeout, bPermissionDenied, bLocationUnavailable, message) {
                        if (bTimeout) {
                            Ext.Msg.alert('Error', 'Timeout occurred.');
                        } else {
                            Ext.Msg.alert('Error', 'Error occurred');
                        }
                    }
                }
            });
            geo.updateLocation();
        } else {
            Ext.Msg.alert('Error', 'No class found');
        }
    },

and the WeatherView where is button created;

    Ext.define('MyApp.view.dash.WeatherView', {
    extend: 'Ext.panel.Panel',
    xtype: 'weatherview',

    requires: [
        'MyApp.view.weather.WeatherData',
        'MyApp.view.weather.WeatherWindow',
        'MyApp.view.weather.WeatherUtil'
    ],

    closable: false,
    resizable: false,
    title: 'Weather',
    itemId: 'weatherView',
    iconCls: 'x-fa fa-bell',
    height: 400,

    cls: 'quick-graph-panel shadow',
    layout: 'fit',

    tools: [
        {
            type: 'refresh',
            handler: 'refreshGeoLocation'
            // listeners: {
            //     click: 'refreshGeoLocation'
            // }
        },
        {
            type: 'gear',
            handler: 'weatherWindow'
        }
    ],
    // html: 'Welcome to our weather app. Click on refresh to get the latest weather information',

    items: [{
        xtype: 'weatherdata'
    }],

    listeners: {
        beforerender: 'getGeolocation'
    }
});

Solution

  • For this you need to store latitude and longitude in application. You can use singleton of ExtJS. This singleton accessible throughout application whenever you need this.

    I have updated my ExtJS-GeoLocation library please see.

    Code Snippet

    Singleton class example

    Ext.define("GeoLocation.util.CommonUtility", {
        singleton: true,
        alternateClassName: 'commonutility',
        config: {
            latitude: 0,
            longitude: 0
        },
        constructor: function (config) {
            this.initConfig(config);
        }
    });
    

    Data view example with store here

    /**
     * This class is the main view for the application. It is specified in app.js as the
     * "mainView" property. That setting automatically applies the "viewport"
     * plugin causing this view to become the body element (i.e., the viewport).
     *
     * TODO - Replace this content of this view to suite the needs of your application.
     */
    Ext.define('GeoLocation.view.main.Main', {
        extend: 'Ext.tab.Panel',
        xtype: 'app-main',
    
        requires: [
            'Ext.plugin.Viewport',
            'Ext.window.MessageBox',
            'GeoLocation.view.main.MainController',
            'GeoLocation.util.Geolocation'
        ],
        controller: 'main',
        ui: 'navigation',
        //tabBarHeaderPosition: 1,
        titleRotation: 0,
        tabRotation: 0,
        activeTab: 0,
        items: [{
            title: 'Geo Location',
            iconCls: 'x-fa fa-map',
            itemId: 'geoLocation',
            items: [{
                xtype: 'button',
                text: 'Check weather',
                handler: 'onWeatherButtonClick'
            }, {
                xtype: 'dataview',
                store: {
                    fields: [{
                        name: 'summary',
                        mapping: 'weather[0].main'
                    }, {
                        name: 'description',
                        mapping: 'weather[0].description'
                    }],
                    proxy: {
                        type: 'jsonp',
                        url: `http://api.openweathermap.org/data/2.5/weather?lat=${commonutility.getLatitude()}&lon=${commonutility.getLongitude()}&units=metric&appid=9b59049894d42af608baf69f869b9ace`,
                        reader: {
                            type: 'json'
                        }
                    },
                    autoLoad: true
                },
                itemTpl: '<div class="weather-image-container"><img src="../../../resources/img/ico_cloud.png" alt="{summary}"/></div>' +
                    '<div class="weather-details-container">' +
                    '<div>{main.temp}&#176;</div>' +
                    '<div>{summary}</div>' +
                    '<div>{description}</div>' +
                    '</div>'
            }]
        }],
        listeners: {
            beforerender: 'onMainViewRender'
        }
    });