Cannot select JSON elements - javascript

I'm brand new to web dev but I'm trying to create a Weather app using the openweatherapp API: https://openweathermap.org/current#geo . The JSON object is below:
{"coord":{"lon":5.38,"lat":34.72},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"base":"stations","main":{"temp":280.903,"pressure":1000.23,"humidity":65,"temp_min":280.903,"temp_max":280.903,"sea_level":1031.37,"grnd_level":1000.23},"wind":{"speed":8.5,"deg":317},"clouds":{"all":0},"dt":1486603649,"sys":{"message":0.3449,"country":"DZ","sunrise":1486621797,"sunset":1486660553},"id":2475612,"name":"Tolga","cod":200}
Here's my javascript:
$(document).ready(function() {
// findind my latitude and longitude
if(navigator.geolocation){
function success(position){
var lat = position.coords.latitude.toString();
var long = position.coords.longitude.toString();
$("p").html("latitude: " + lat + "<br>longitude: " + long);
// using the API to get the weather from those lat and long values
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long+"&appid=6a5aa3b59ebd571086cbd82be484ec8b", function(a){
temp = a[0].main.temp.toString();
hum = a[0].main.humidity.toString();
press= a[0].main.pressure.toString();
name = a[0].name;
$("h1").html(temp);
});
};
};
function failure(){
$("p").html("Not working");
};
navigator.geolocation.getCurrentPosition(success,failure);
});
The lat and long part is running fine but not the API for the weather.
Any help would be appreciated.
EDIT: Here's my codepen to make it simpler : https://codepen.io/tadm123/pen/OWojPx

Worked fine for me. Make sure that your browser has permission to know your location and that the computer has GPS. This probably will not work on a desktop.
Try manually setting the lat and long values and it should work.

Related

Display local weather and time on a website

I am a bit of a novice to programming and have started to dive into JavaScript lately. I am trying to create a small widget on a website I am helping a friend build. I want to build a widget on the website that displays the current local time for the user browsing, but also his location and the weather at his or her location.
So far, I have managed to create the script to display the local time for the user, but what I cannot figure out is the weather app.
My idea is to request the IP address from the client and link that to a geo location and lastly a weather API. Again, I am quite a novice in this field so any help would be appreciated. Feels like I have been Googling without any success for the last two days.
So far, I have the following code for the local time.
<!DOCTYPE html>
<html>
<head>
<style>
table {
font-family:Arial, Helvetica, sans-serif;
font-size:24px;
}
</style>
<script>
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
</head>
<body onload="startTime()">
<table>
<tr><td>Current Local Time:</td><td><div id="txt"</div></tr><td></td>
</div>
</table>
</body>
</html>
thats a great project for learning javascript. The more experienced you get with javascript the more you will learn about the different api features of the browser. One of these features is the navigator to ask the user for permission for geolocation and to retrieve the data:
navigator.geolocation.getCurrentPosition( (data) => console.log(data) )
The following link gives you a great and more detailed Overview about Geolocation possibilities of the browser -> html geolocation
You can now send these values to a backend which maps from geolocation to weahterinformation.
first try to get user's location
now you need to use an api and filter by that location
to do that there is many ways that can help depending on the Api here is some suggestion you will find
some apis uses longitude and latitude and others uses location name.
so in this example you will get the latitude and longitude of user location and then use them like the following in a fetch method that is GET Method by default .
<script>
const getlocation = () => {
navigator.geolocation.watchPosition(async(pos) => {
var lat = pos.coords.latitude;
var long = pos.coords.longitude;
const url = "https://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long;
const response = await fetch(url);
const data = await response.json();
console.log(data);
});
}
</script>
the data will be in json
so you can jump into any necessary variables in json object and get it for example
if you get
{
"coord": { "lon": 139,"lat": 35},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01n"
}
],......
you can create a variable and get weather by doing this
const result = data.weather[0];
var id = result.id
Note the URL not working and you need to have a valid API key or use another one if you have.

Passing Multiple Variables to HTML via Javascript

I am trying to pass a latitude AND a longitude from one page to another after it has been calculated by the google API.
For a compass website. Want to pass the lat and long both to another page to be used on that page. I am trying to pass them via the javascript.
The Java passing the variables.
var lat = marker.getPosition().lat();
var long = marker.getPosition().lng();
window.location.href = 'compass.html' + '#' + lat +'#' + long;
The Java recieving the variables
var latD = window.location.hash.substring(1);
var longD = window.location.hash.substring(2);
Instead of being split up they and being displayed together on the other page with the hash included. Like this:
-41.2864603?#174.77623600000004,
41.2864603?#174.77623600000004
I would like it to be like this:
-41.2864603
,174.77623600000004
Hash
The idea works, you just need to split the hash-string correctly.
//REM: On whatever.html
var lat = '-41.2864603';
var long = '174.77623600000004';
var tHref = 'compass.html' + '#' + lat +';' + long; //window.location.href = ..
//REM: On compass.html
var tHash = tHref.split('#').pop(); //window.location.hash.split('#').pop();
var tLat = tHash.split(';')[0];
var tLong = tHash.split(';')[1];
alert('Lat: ' + tLat + ', Long: ' + tLong);
QueryString
As another approach you could pass it as normal QueryString value like nbokmans recommended. Either separate or as stringified object. The difference is, that you need to implement your own js QueryString-Parser unless you get the values on the server. But you will find plenty of QueryString-Parsers on google.
Here is an example:
How can I get query string values in JavaScript?
localStorage
localStorage sounds like the easiest solution for me. You do not need to implement your own QueryString-Parser for it aswell. Just set it on whatever.html and read it on compass.html.
Check the example below:
https://developer.mozilla.org/de/docs/Web/API/Window/localStorage
//Set:
window.localStorage.setItem('whatever', JSON.stringify({lat: 1, long:2}));
//Get:
JSON.parse(window.localStorage.getItem('whatever'));
it should be like this :
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();
window.location.href = 'compass.html?lat=' + '' + lat +'&longt=' + long;
To access these variables on that page,
const queryString = window.location.search;
console.log(queryString); // ?lat=19.234567&longt=73.23456
const urlParams = new URLSearchParams(queryString);
const lat = urlParams.get('lat')
const lng = urlParams.get('longt')
console.log(lat, lng);

JS parseFloat creates Int when parsing ASP.NET MVC model data

I want to parse Model data as a float to Javascript variable, but I will always get no decimals
function initMap() {
var latitude = parseFloat("#Model.latitude");
var longitude = parseFloat("#Model.longitude");
console.log(latitude + " " + longitude);
}
For example, if Model.latitude = 46.3245 I will get 46.
I have also tried this: var latitude = parseFloat("#Model.latitude").toFixed(4); but I get 46.0000
What can I do ?

Sort data based on my location and predefine city name

I am Using AngularJs and Ionic for Hybrid Mobile App development.
I am getting this data from API
[{"Location":"Brierfield"},
{"Location":"Centreville"},
{"Location":"Chelsea"},
{"Location":"Coosa Pines"},
{"Location":"Clanton"}]
With the help of below code I am getting my current location
var position = {};
var onSuccess = function(position2) {
console.log(position2.coords.latitude )
console.log(position2.coords.longitude)
position.latitude = position2.coords.latitude;
position.longitude = position2.coords.longitude;
$rootScope.$digest()
};
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
return position;
I have to check based on my current location and above data(Location) which city is near by me and based on that I need to sort my data in View.
It will be great if you can get lat & long data of the locations from the api. Getting your current position and location data you can use Haversine Formula to calculate the distance between two points.
In case you are not able to get position details from API then you have to get the coordinates of the location and use the Haversine Formula.
Hope this will solve your problem.

How can i solve a javascript error "undefined" is not a object when using google.maps.geometry.spherical.computeOffset?

So, i am playing with javafx and google maps and using the javascript api so i came around the following problem.
To clarify i am using the following script source:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
I have the javascript function:
document.goToLocation = function goToLocation(x, y) {
var latLng = new google.maps.LatLng(x, y);
var eastPoint = new google.maps.geometry.spherical.computeOffset(latLng, 2000, 90));
marker.setPosition(latLng);
map.setCenter(latLng);
}
Inside my class i have the following lines of code:
webEngine.executeScript("" +
"window.lat = " + lat + ";" +
"window.lon = " + lon + ";" +
"document.goToLocation(window.lat, window.lon);"
};
The problem come from the line:
var eastPoint = new google.maps.geometry.spherical.computeOffset(latLng, 2000, 90));
When i comment this line my program works great and the map appears.
When i don't comment this line i get the following error:
netscape.javascript.JSException: TypeError: 'undefined' is not an object
at com.sun.webpane.platform.WebPage.twkExecuteScript(Native Method)
at com.sun.webpane.platform.WebPage.executeScript(WebPage.java:1438)
at javafx.scene.web.WebEngine.executeScript(WebEngine.java:811)
at utils.gmaps.WebMap$MyBrowser$2.handle(MyClass.java:77)
where line 77 is the line for the execute script function.
What is going on and how can i fix it?
Please help
Ciprian
It was indeed my fault because i did load the correct library. After i managed to get the code right the application worked.
Thank you

Categories

Resources