All in this code I'm trying to give user location and Temperature in locality But somehow temperature is showing way less in Celsius and also not updating below is what I tried like it is 4-5 Hours Back Data that to 10 degree Celsius less like if temp is 22(Celsius) hours back it is showing like 3(Celsius) working Example On codepen http://codepen.io/cannelflow/full/RrymYo/
var x = document.getElementById("demo");
var y = document.getElementById("demo1");
window.onload = getLocation();
//window.onload=getWeather();
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
//Location For Display
function showPosition(position) {
var loc = { lat: position.coords.latitude, lon: position.coords.longitude };
getWeather(loc);
var baseURL = "https://maps.googleapis.com/maps/api/geocode/json?latlng=";
var fullURL = baseURL + loc.lat + "," + loc.lon;
$.ajax({
url: fullURL,
success: function (display) {
x.innerHTML = display.results[1].formatted_address;
}
});
}
//Location For Weather
function getWeather(loc) {
var baseURL = "http://api.openweathermap.org/data/2.5/weather?lat=";
var appid = "064129b86c99c35c42d531db251b99e3";
var fullURL = baseURL + loc.lat + "&lon=" + loc.lat + "&appid=" + appid + "&units=metric";
//http://api.openweathermap.org/data/2.5/weather?lat=21.2600668&lon=81.5989561&appid=064129b86c99c35c42d531db251b99e3&units=metric
$.ajax({
url: fullURL,
success: function (display1) {
y.innerHTML = display1.main.temp;
}
});
}
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
<body>
<section>
<div class="container-fluid text-center">
<br />
<!-- <h1><button class="btn btn-danger" onclick="getLocation()">Click Me To Get Your Location!</button></h1> -->
<h1 class="text-primary" id="demo1"></h1>
<br />
<h1 class="text-primary" id="demo"></h1>
</div>
</section>
</body>
You have a typo:
var fullURL = baseURL + loc.lat + "&lon=" + loc.lat + "&appid=" + appid + "&units=metric";
should be
var fullURL = baseURL + loc.lat + "&lon=" + loc.lon + "&appid=" + appid + "&units=metric";
You have a typo in the query string. A better alternative is to user jQuery.param to build the query string from an object instead as its easier to read and thus less error prone.
function getWeather(loc) {
var baseURL = "http://api.openweathermap.org/data/2.5/weather?";
return $.ajax({
url: baseURL + $.param({
appid: "064129b86c99c35c42d531db251b99e3",
lon: loc.lon,
lat: loc.lat,
units: "metric"
}),
success: function(display1) {
y.innerHTML = display1.main.temp;
}
});
}
Modified It Like
function getWeather(loc) {
var baseURL = "http://api.openweathermap.org/data/2.5/weather?lat=";
var appid = "064129b86c99c35c42d531db251b99e3";
//var fullURL = baseURL + loc.lat + "&lon=" + loc.lat + "&appid=" + appid + "&units=metric";
//http://api.openweathermap.org/data/2.5/forecast?lat=35&lon=139&appid=44db6a862fba0b067b1930da0d769e98&units=metric
$.ajax({
url: baseURL,
type: 'get',
dataType: 'JSONP',
data: { lat: loc.lat, lon: loc.lon, units: 'metric', APPID: appid },
success: function (data) {
y.innerHTML = data['main']['temp'] + " °C";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
And It Worked
Related
I want the longitude and latitude passed from the geolocation function to my getjson function so that i can pull certain info like temperature, condition etc. What am i doing wrong that the lati and loni are not being passed properly? Are my functions set up correctly?
$(window).load(function() {
getLocation();
apiCall();
}); //run immediately on page load
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var lati = position.coords.latitude;
var loni = position.coords.longitude;
function passData(lati, loni);
}
var weath = 0;
function apiCall() {
function passData(latitude, longitude) {
var lati = latitude;
var loni = longitude;
x.innerHTML = "Latitude: " + lati +
"<br>Longitude: " + loni;
}
//$(".city").html(data.city + "," + "" + data.countryCode);
$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=" + lati + "&lon=" + loni, function(data1) {
weath = Math.round(data1.main.temp);
$(".temp").html(weath + " " + "℃");
$(".condition").html(data1.weather[0].description);
$(".iconDisplay").append('<img src=' + data1.weather[0].icon + '/>');
}); /*end of json*/
};
One of my recent projects is to successfully get the temperature to convert from Fahrenheit to Celsius. However, I have run into a problem that gives me an undefined value when I click my button. Should I be referring to the temperature value that I have requested from my API? I believe that my conversion within my weather function isn't running when I call it.
Here's my codepen.
https://codepen.io/baquino1994/pen/qXjXOM?editors=0010
HTML
<span id="temp"></span>
<button id="tempunit">F</button>
JS
function weather(){
function success(position){
var latitude = position.coords.latitude;
var longitude= position.coords.longitude;
// location.innerHTML = "Latitude:" + latitude+"°"+ "Longitude: " + longitude+'°';
var theUrl = url +apiKey + "/"+ latitude+","+ longitude +"?callback=?";
$.getJSON(theUrl, function(data){
$("#temp").html(data.currently.temperature)
$("#minutely").html(data.minutely.summary)
// currentTempInFahrenheit = Math.round(data.html.currently.temperature * 10) /
$("#tempunit").text(tempUnit);
$.ajax({
url:'https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=AIzaSyBpiTf5uzEtJsKXReoOKXYw4RO0ayT2Opc', dataType: 'json',
success: function(results){
$("#city").text(results.results[3].address_components[4].long_name)
$("#country").text(results.results[0].address_components[5].long_name)
}
}
)}
);
}
var location = document.getElementById("location");
var apiKey = "3827754c14ed9dd9c84afdc4fc05a1b3";
var url = "https://api.darksky.net/forecast/";
navigator.geolocation.getCurrentPosition(success);
// location.innerHTML = "Locating...";
}
$(document).ready(function(){
weather();
});
var tempUnit = "F";
var currentTempInFahrenheit;
$("#tempunit").click(function(){
var currentTempUnit = $("#tempunit").text();
var newTempUnit = currentTempUnit == "F" ? "C" : "F";
$('#tempunit').text(newTempUnit);
if(newTempUnit == "F"){
var celTemp = Math.round(parseInt($('#temp').text())*5/9 - 32);
$("#temp").text(celTemp + " " + String.fromCharcode(176));
}
else{
$("#temp").text(currentTempInFahrenheit + " " + String.fromCharCode(176));
}
})
try this, my browser blocked geolocation, when i mocked the location i was able to get the codepen to work.
var location = document.getElementById("location");
var apiKey = "3827754c14ed9dd9c84afdc4fc05a1b3";
var url = "https://api.darksky.net/forecast/";
// navigator.geolocation.getCurrentPosition(success);
var position = { coords: { latitude: 32, longitude: -96 } };
success(position);
I am making a basic web-based weather app, which detects the current weather conditions in the user's location. My current code so far does work, but is missing an important feature - I want the background of the web page to change according to the user's location and weather conditions. For instance - if a user is in New York and the weather is sunny, I would like to display any New York based popular image(ex: Times Square) along with sunny skies as the body background. I've searched several APIs but haven't found any that meets my needs.
In my current code, I'm using IPInfo.io to get the user's location and OpenWeatherMap to get the weather conditions.
This pen has my code (NOTE - code for units hasn't been added yet), and here's the JS bit -
var lat = 0.0,
lon = 0.0;
var testURL = 'http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=2de143494c0b295cca9337e1e96b00e0';
var myURL = 'http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&appid="ae0acb60e8db4952e081c2fb470a1b23"';
var city = '',
state = '',
country = '',
postal = 0;
//if (navigator.geolocation) {
// /* geolocation is available */
// navigator.geolocation.getCurrentPosition(function (position) {
// lat = position.coords.latitude;
// lon = position.coords.longitude;
// console.log("Latitude = " + lat);
// console.log("Longitude = " + lon);
//
// display(position.coords.latitude, position.coords.longitude);
// });
//
//} else {
// /* geolocation IS NOT available */
// $("#jumbotron").html("geolocation not available");
//
//}
//get co-ordinates using ipinfo.io
$.getJSON('http://ipinfo.io', function (data) {
console.log(data);
var loc = data.loc;
lat = loc.split(",")[0];
lon = loc.split(",")[1];
display(lat, lon);
city = data.city;
state = data.region;
country = data.country;
postal = parseInt(data.postal, 10);
})
function display(x, y) {
$("#pos1").html("<b>" + x + "</b>");
$("#pos2").html("<b>" + y + "</b>");
}
//function to calculate wind direction from degrees
function degToCompass(num) {
//num = parseInt(num, 10);
console.log("Inside degtocompass = " + num);
var val = Math.floor((num / 22.5) + 0.5);
var arr = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"];
return arr[(val % 16)];
}
//function to return current temperature
function convertTemp(currTemp) {
//get celsius from kelvin
return Math.round(currTemp - 273.15);
}
$("button").click(function () {
console.log("In Latitude = " + lat);
console.log("In Longitude = " + lon);
//prepare api call
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&appid=ae0acb60e8db4952e081c2fb470a1b23',
//url: testURL,
type: 'GET', // The HTTP Method, can be GET POST PUT DELETE etc
data: {}, // Additional parameters here
dataType: 'json',
success: function (data) {
console.log(data);
//---------get the clipart---------------
var picLink = 'http://openweathermap.org/img/w/';
var picName = data.weather[0].icon;
picLink += picName + ".png";
$("#picture").empty().append('<img src="' + picLink + '">');
//----------get the temperature-----------
var curTemp = convertTemp(data.main.temp);
console.log("Current temp = " + curTemp);
//$("#temp").empty().append("<b>" + curTemp + "</b>");
$("#picture").append("<b>" + curTemp + "</b>");
//----------get the place----------------------
var area = city + ", " + state + ", " + country;
$("#area").empty().append("<b>" + area + "</b>");
//----------get weather conditions------------
$("#conditions").empty().append("<b>" + data.weather[0].description + "</b>");
//----------get wind speed------------
//get wind direction
var windSpeed = degToCompass(data.wind.deg);
//add wind speed
windSpeed += ' ' + data.wind.speed;
//display wind speed
$("#wind-speed").empty().append("<b>" + windSpeed + "</b>");
},
error: function (err) {
alert(err);
},
beforeSend: function (xhr) {
//xhr.setRequestHeader("X-Mashape-Authorization", "32ROUuaq9wmshfk8uIxfd5dMc6H7p1lqdZSjsnXkB5bQtBteLK"); // Enter here your Mashape key
}
});
});
Well... First of all there is no need to use WebServices, but you can't do it without any API. As I can see you use openweathermap API . As far as I know this API returns both longitude and latitude, so you can use these values as input to another request to a photo API (like flickr) to get the image you want. Moreover openweathermap API returns city name which can make your photo request even more accurate.
var x = document.getElementById("demo");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
function showPosition(position) {
var location = position.coords.latitude +
"," + position.coords.longitude;
jQuery(document).ready(function($) {
$.ajax({
url : "https://api.wunderground.com/api/0ce1c4a981f7dd2a/geolookup/conditions/q/"+location+".json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
x.innerHTML = "Current temperature in " + location + " is: " + temp_f;
var forecast = parsed_json['forecast']['txt_forecast']['forecastday'];
for (index in forecast) {
var newForecastString = '' + forecast[index]['title'] + ' سيكون ' + forecast[index]['fcttext_metric'];
var newForecastParagraph = $('<p/>').text(newForecastString);
$(".astro").append(newForecastParagraph);
}
}
}});
I'm trying to make a weather that first checks for jQuery on a page and loads the library if necessary, before loading my custom script. The script looks like this
This is the corrected one.
You can test your javascript here: http://www.javascriptlint.com/online_lint.php
var x = document.getElementById("demo");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
function showPosition(position) {
var location = position.coords.latitude + "," + position.coords.longitude;
jQuery(document).ready(function($) {
$.ajax({
url : "https://api.wunderground.com/api/0ce1c4a981f7dd2a/geolookup/conditions/q/"+location+".json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
x.innerHTML = "Current temperature in " + location + " is: " + temp_f;
var forecast = parsed_json['forecast']['txt_forecast']['forecastday'];
for (index in forecast) {
var newForecastString = '' + forecast[index]['title'] + ' سيكون ' + forecast[index]['fcttext_metric'];
var newForecastParagraph = $('<p/>').text(newForecastString);
$(".astro").append(newForecastParagraph);
}
}
});
});//add this code. Need to close the 'jQuery(document)'
} // added this code. Need to close the function showPosition
Last line is missing ) in second position. it should be })});
the last 3 lines of your code are as follows
}
}
}});
however, they should be
}
}
}); // you missed this );
});
} // you missed this }
I'm using google maps and rendering many markers at http://www.dentalo.se/search/stockholm and it is working fine.
What I would like to do is when someone clicks on a button I want to use map.SetCenter and focus on that location.
I have a Information button
when a user clicks on it I am calling a JavaScript function and setting the center. But is not working. When I click on information it just becomes gray. You can try it yourself and see what happpenes at http://www.dentalo.se/search/stockholm.
function showCompany(latlong) {
map.setCenter(latlong);
alert(latlong);
}
This is the jquery code for rendering the map
var p = $("#map_search");
var position = p.position();
$("#directionsPanel").css({top: position.top, position:'absolute'});
var map;
var addressField;
var geocoder;
$(document).ready(function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(ShowPosition);
}
else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.");
break;
}
}
function ShowPosition(position) {
//begin rest call
$("#latitude").val(position.coords.latitude);
$("#longitude").val(position.coords.longitude);
var from = $("#latitude").val() + "," + $("#longitude").val();
var urlParts = window.location.href.split('/'),
Id = urlParts[(urlParts.length - 1)];
$.ajax({
type: "GET",
cache: true,
async: false,
url: "/RestService/Dentalo.svc/CompaniesByState/" + Id,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
map = new GMaps({
el: 'map_search',
//center: Id,
lat: data[0].State.Latitude ,//position.coords.latitude,
lng: data[0].State.Longitude,
zoom: 14,
zoomControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DEFAULT,
position: google.maps.ControlPosition.RIGHT_RIGHT
},
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.RIGHT_TOP
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.RIGHT_TOP
},
panControl: true,
scrollwheel: true
});
map.addMarker({
lat: position.coords.latitude,
lng: position.coords.longitude,
title: 'Min position',
icon: 'http://www.dentalo.se/assets/img/map/user_x64.png'
});
var h = "";
$.each(data, function (index, item) {
var to = item.Latitude + "," + item.Longitude;
h += "<div class='row buttons-page'>" +
"<div class='col-md-8 col-sm-4'>" +
"<h4>"+ item.Name + "</h4>" +
"<p style='margin: 1px;'>" + item.Address + ", " + item.County.Name + "</p>" +
"<p style='margin: 1px;'>" + item.Phone + "</p>" +
"<p style='margin: 1px;'>Distans: " + calcRoute(from, to) + "</p>" +
"</div>" +
"<div class='col-md-3 col-sm-9'>" +
"<div class='btn-group'>" +
"<a href='/booking/"+ item.CompanyId +"' class='btn " + bookable(item.Status) + " " + SetDisplayClass(item.Status) +"'>Boka <i class='m-icon-swapright m-icon-white'></i></a>" +
"<button type='button' class='btn default' onClick='showCompany('" + to + "');return false;'>Information <i class='icon-info-sign m-icon-white'></i></button>" +
"</div>" +
"</div>" +
"</div>" +
"<hr style='margin: 1px;' />";
map.addMarker({
lat: item.Latitude ,
lng: item.Longitude ,
title: item.Address ,
icon: GetMarkerImage(item.Status),
infoWindow: {
content: '<div style="width: 300px"><h4>' + item.Name + '</h4><br /><p>' + item.Address + ', ' + item.County.Name + '</p><div class="four columns alpha"><a class="btn blue ' + SetDisplayClass(item.Status) + '" href="/booking/' + item.CompanyId + '" ><i class="m-icon-swapright m-icon-white"></i> Boka</a> Information</div></div>',
}
})
});
$("#search_panel").html(h).show();
},
error: function (msg, url, line) {
//alert('error trapped in error: function(msg, url, line)');
alert('msg = ' + msg + ', url = ' + url + ', line = ' + line);
}
});
//end rest call
// Define Gecoder
geocoder = new google.maps.Geocoder();
// Init searchbox
initSearchBox();
// main directions
}
How can I set SetCenter when a user clicks on the "Information" button?
Thanks in advance.
map.setCenter(latlong);
latlong must be a google.maps.LatLng object but in your case you are passing a string to your function.
<button onclick="showCompany('59.3618356,18.0140273');return false;">Information</button>
So that won't work.
Instead try:
<button onclick="showCompany('59.3618356','18.0140273');return false;">Information</button>
And
function showCompany(lat, lng) {
var position = new google.maps.LatLng(lat, lng);
map.setCenter(position);
alert(lat, lng);
}