How to get the values from JS in models.py file - javascript

How to get the values of JS in models.py file.
I created the model of weather information where current weather fetch from latitude and longitude. I used the api of openweathermap.org but unable to get the data of current location.
I used the following to code.
.py file
WEATHER_API_LAT_LON = "%s/weather?appid=%s&units=metric&lat={}&lon={}" % (API, APP_ID)
#api.multi
def get_weather_info(self,lat, lon):
url = WEATHER_API_LAT_LON.format(lat, lon)
print(url)
.js file
var GetLocation = function getLocation() {
if (navigator.geolocation) {
return navigator.geolocation.getCurrentPosition(showPosition);
}
else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
console.log(lat);
console.log(lon);
}
From JS get the location and merge to .py model lat and lon.
Anyone can tell how to do this.

For Odoo 10
*model.py
#api.multi
def get_weather_info(self,lat, lon):
url = WEATHER_API_LAT_LON.format(lat, lon)
print(url)
return url
*.js
// on header
var Model = require('web.Model');
// inside main function
var model = new Model('model.name').call('get_weather_info',[]).then(function(result){
console.log(result)
});
For Odoo 11
*.js
var self = this;
self._rpc({
model: 'model.name',
method: 'get_weather_info',
}, []).then(function(result){
console.log(result)
})
pass your lat and lon in the array while calling method in model.py

*.model.py
#api.multi
def get_weather_info(self,lat, lon):
url = WEATHER_API_LAT_LON.format(lat, lon)
print(url)
*.js for odoo 11
var self = this;
self._rpc({
model: 'model.name',
method: 'get_weather_info',
args: [], //Here you have to pass the arguments using keyword agrs.
}).then(function(result){
console.log(result)
})

Related

Javascript Unexpected run order

I have this jquery / javascript code below. It ask user for location permission, and then outputs a URL string with latitude appended at the end.
I put 3 console.log statemnets to highlight problem, with current outputs I get.
Expected Debug Values (in order)
1_lat =95.555555
2_lat =95.555555
3_https://fcc-weather-api.glitch.me/api/current?&lat=95.555555
Actual Debug Values: (in order)
2_
3_https://fcc-weather-api.glitch.me/api/current?&
1_lat =95.555555
var curLat ='';
var curLon ='';
var weatherAPI='';
$(document).ready(function(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
curLat = "lat=" + position.coords.latitude;
console.log("1_", curLat);
});
}
weatherAPI = getURL(curLat);
console.log("3_", weatherAPI);
});
function getURL(lat){
console.log("2_", lat);
var url = "https://fcc-weather-api.glitch.me/api/current?";
url = url + "&" + lat;
return url;
}
I must not be understanding something with how javascript is loading and how jQuery document.ready.function is affecting the results.
navigator.geolocation is async. So you have to wait for the navigator.geolocation.getCurrentPosition callback function before you can process the lat and lng
You can do something like this:
var curLat ='';
var curLon ='';
var weatherAPI='';
$(document).ready(function(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
curLat = "lat=" + position.coords.latitude;
console.log("1_", curLat);
weatherAPI = getURL(curLat);
console.log("3_", weatherAPI);
});
}
});
function getURL(lat){
console.log("2_", lat);
var url = "https://fcc-weather-api.glitch.me/api/current?";
url = url + "&" + lat;
return url;
}
This will result to:
1_ lat=1.xxx
2_ lat=1.xxx
3_ https://fcc-weather-api.glitch.me/api/current?&lat=1.xxx

Very simple API call that doesn't return anything

I'm trying to get data from the open weather API but all I get is an object that I cannot use (the JSON is inside but I cannot access it)
I've read a lot about asynchronous JS and callbacks. I'm really not sure whether I need a callback for EACH API i'm using, I already used one to get latitude and longitude but now, for the open weather API, i need to pass these lat and lon as parameters for the API call, and I have no idea on how to do that if I use callbacks (as it seems that arguments in callbacks functions are not the ones used in the function but the ones that actually get returned, which I find extremely confusing).
Can anyone tell me what I'm doing wrong here?
$(document).ready(function() {
$('#getWeather').on('click', function(){
myLatAndLon(function(result) {
var lat = result[0];
var lon = result[1];
console.log(myWeather(lat, lon));
// Here, although the params work in browser, the message that gets returned in console is : "NS_ERROR_DOM_BAD_URI: Access to restricted URI denied"
});
})
})
function myLatAndLon(callback) {
$.getJSON('http://ip-api.com/json/').done( function(location) {
var arr = [];
arr.push(location.lat);
arr.push(location.lon);
callback(arr);
});
}
function myWeather(lat, lon) {
return $.getJSON('http://api.openweathermap.org/data/2.5/weather', {
lat: lat,
lon: lon,
APPID: 'a9c241803382387694efa243346ec4d7'
})
// The params are good, and when I type them on my browser, everything works fine
}
Change your code to it and test again :
$(document).ready(function() {
$('#get').on('click', function() {
myLatAndLon(function(result) {
var lat = result[0];
var lon = result[1];
alert(JSON.stringify(result));
$req = myWeather(lat, lon);
$req.done(function(R) {
alert(JSON.stringify(R))
});
});
})
})
function myLatAndLon(callback) {
$.getJSON('//ip-api.com/json/').done(function(location) {
var arr = [];
arr.push(location.lat);
arr.push(location.lon);
callback(arr);
});
}
function myWeather(lat, lon) {
return $.getJSON('//api.openweathermap.org/data/2.5/weather', {
lat: lat,
lon: lon,
APPID: 'a9c241803382387694efa243346ec4d7'
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="get">get</button>
And also you should check your server for CORS limitations read more here:
http://enable-cors.org/server.html

show local weather using openweathermap api

I am going to make a web app that show local weather using openweathermap api.
When I click the button, an IP API was called to get the co-ordinate of my location(longitude and latitude). These information then was used with API key (I registered in the website openweathermap.org) to create URL to call weather info according to the APIdocs, then change the HTML element with the data got from the server. I doing this on codepen. I tried to do the simplest one but it doesn't work.
<h1>weather forcast</h1>
<button id="btn">view</button>
<p id ="test">change me</p>
<p id ="place">place</p>
<p id ="temp">temperature</p>
<p id ="description">description</p>
var getLocation = function(data) {
var lat = data.lat;
var lon = data.lon;
var apiKey = "[APIKEY]";
};
var url = 'http://api.openweathermap.org/data/2.5/weather?' + 'lat=' + lat + '&lon=' + lon + '&appid=' + apiKey;
//call back function to extract weather info.
var getWeather = function(data) {
var temp = data.main.temp;
var description = data.weather[0].description;
var place = data.name;
};
$(document).ready(function() {
$("#btn").click(function() {
$.getJSON('http://ip-api.com/json', getLocation, 'jsonp')
$.getJSON(url, getWeather, 'jsonp');
$("#test").text("I AM CHANGED. THANKS!")
$("#temp").text(temp)
$("#description").text(description)
$("#place").text(place)
})
})
You have several issues. The first is that the $.getJSON calls are asynchronous, so the text() of the elements will be changed before any request completes. You need to place all code dependant on the values returned from the request in the callback functions.
Secondly you have issues with variable scope where you're defining your variables inside the function and then attempting to use them outside where they will be undefined.
With that said, you need to re-arrange your logic to something like this:
var getWeather = function(data) {
$.getJSON('http://api.openweathermap.org/data/2.5/weather', {
lat: data.lat,
lon: data.lon,
appid: "[APIKEY HERE]"
}, showWeather, 'jsonp');
};
var showWeather = function(data) {
$("#test").text("I AM CHANGED. THANKS!")
$("#temp").text(data.main.temp)
$("#description").text(data.weather[0].description)
$("#place").text(data.name)
};
$(document).ready(function() {
$("#btn").click(function() {
$.getJSON('http://ip-api.com/json', getWeather)
})
})
Note that the function calls are chained from the event (ie the click makes the location AJAX request, which calls getWeather which then calls showWeather. Also note how the variables are now local and used within their own function scope.
Finally, check that you're using the correct data formats for the AJAX requests. ip-api.com/json is returning JSON, not JSONP.
You can get data about the location with use third-party API. for example:http://ip-api.com/.
You get your location weather data from OpenWeatherMap service using the ip-api. its help you to get visitor location weather.
var getIP = 'http://ip-api.com/json/';
var openWeatherMap = 'http://api.openweathermap.org/data/2.5/weather'
$.getJSON(getIP).done(function(location) {
$.getJSON(openWeatherMap, {
lat: location.lat,
lon: location.lon,
units: 'metric',
APPID: 'Your-Openweather-Apikey'
}).done(function(weather) {
$('#weather').append(weather.main.temp);
console.log(weather);
})
})

How can i get latitude and longitude coordinates from JSON Google Maps

I know what i can get JSON LatLon (and other) data indicate my address in the URL
app.factory('myCoordinates', function myCoordinates($q, $http) {
var deferred = $q.defer();
$http.get('http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region')
.success(function(coordinates) {
var myCoordinates = {};
myCoordinates.lat = coordinates.results[0].geometry.location.lat;
myCoordinates.lng = coordinates.results[0].geometry.location.lng;
myCoordinates.zoom = 14;
deferred.resolve(myCoordinates);
})
return deferred.promise;
});
http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region
But how can i get latitude and longitude coordinates of my current location without input my address in URL (automatically) ?
How about using html5 navigator.geolocation.getCurrentPosition to get the latitude and longitude?
Example:
navigator.geolocation.getCurrentPosition(function(pos){
console.log(pos)
});

Fetch 10000 coordinates synchronously using Google Maps

I want to fetch coordinates of 10,000 line of data using Google Maps geocoding API, and print each line to browser.
My approach is to loop each line (contain address) and pass it to Google Maps URL, then I parse those JSON data to get its lat and lng. I use jQuery.
But the problem here is it seems to run asynchronously. I have tried to use recursive but it loop without print anything. I have read to set async=false but I dont know where to place it.
Here is my current code
var x = 1;
setInterval(function(){
geturl = 'parse.php?urut='+x;
$.get(geturl, function(get){
url = get;
});
$.getJSON(url, function(data){
var lat = data.results[0].geometry.location.lat;
var lang = data.results[0].geometry.location.lng;
var nama = data.results[0].address_components[1].long_name;
$('table').append("<tr><td>"+x+"</td><td>"+lat+","+lang+"</td><td>"+nama+"</td></tr>");
});
x++;
}, 500);
Any recommendation?
This snippet of code should show you where you went wrong
function getCoords(x) {
geturl = 'parse.php?urut='+x;
$.get(geturl, function(url){
$.getJSON(url, function(data){
var lat = data.results[0].geometry.location.lat;
var lang = data.results[0].geometry.location.lng;
var nama = data.results[0].address_components[1].long_name;
$('table').append("<tr><td>"+x+"</td><td>"+lat+","+lang+"</td><td>"+nama+"</td></tr>");
});
});
}
the $.getJSON is run as part of the success function of the $.get - therefore it will get run only once the $.get is complete
I've shown this as a function, so that the value of x will be correct in the $('table').append line

Categories