I'm trying to define the search city based off the user's longitude and latitude which I'm accessing through .geolocation
When adding the long and lat to my url I get this error
cod : "400" message : "-104.9435462 is not a float"
getLocation();
//Find Location of Device
function getLocation(callback) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getData);
}
}
//Get/set Variables
function getData(position) {
var longitude = position.coords.longitude;
var latitude = position.coords.latitude;
var altitude = position.coords.altitude;
var heading = position.coords.heading;
var speed = position.coords.speed;
var date = position.timestamp;
getWeather(longitude, latitude);
console.log(longitude);
console.log(latitude);
}
//Call OpenWeatherAPI
function getWeather(x, y) {
const apiKey = '';
var url = 'http://api.openweathermap.org/data/2.5/forecast?lat=' + x + '&lon=' + y + '&APPID=280e605c456f0ba78a519edde1a641d3';
$.ajax({
url: url,
success: function(result) {
}
});
}; //END getWeather()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Late answer, but hopefully this will save others time. The error message is misleading.
The error occurs because the longitude, which has a range of -180 to 180, was placed in the latitude, which has a range of -90 to 90.
In the code, getWeather() call was made like this:
getWeather(longitude, latitude);
However, notice that the latitude and longitude (x, y) are ordered (latitude, longitude) in the function:
function getWeather(x, y) {
const apiKey = '';
var url = 'http://api.openweathermap.org/data/2.5/forecast?lat=' + x + '&lon=' + y + '&APPID= removed id';
// additional code
};
Changing the call should resolve the problem:
getWeather(latitude, longitude);
Related
lat, long coordinates are saved from the geocode() function. (user typed a city and street in html input -> received lat,long data in form of (50.4342,8.4324))
how do i put variable latlong inside the waypoint0 value, without receiving errors?
var lat = 50.4342;
var long = 8.4324;
var latlong = lat + ',' + long;
function calculateRoute(platform, coordinates)
{
var router = platform.getRoutingService(),
parameters = {
waypoint0: '', //<- insert latlong variable
waypoint1: '49.998700,8.249140',
mode: 'fastest;car;traffic:enabled',
departure: 'now'};
router.calculateRoute(parameters,
function (result) {
console.log(result);
console.log(latlongstr);
}, function (error) {
console.log("error");
});
}
how do i convert lat and long for the waypoint0 value? if i pass the lat long values inside waypoint0 manually then everything is working but i would like to do it dynamically.
i just starting out with javascript so please dont hate me if its easy to solve.
thank you very much for the help.
Ok i solved it myself.
Do this:
function geocode(platform, street2, city2)
{
var street3 = street2;
var city3 = city2;
var geocoder = platform.getGeocodingService(),
parameters = {
searchtext: street3 + city3 ,
gen: '9'};
geocoder.geocode(parameters,
function (result) {
var lat = result.Response.View[0].Result[0].Location.DisplayPosition.Latitude;
var long = result.Response.View[0].Result[0].Location.DisplayPosition.Longitude;
calculateRoute(platform, lat, long);
}, function (error) {
console.log("Retrieving Latitude and Longitude failed! Refresh the page and try again.");
});
function calculateRoute(platform,latitude,longitude)
{
var x = latitude;
var y = longitude;
var router = platform.getRoutingService(),
parameters = {
waypoint0: x + "," + y,
waypoint1: '49.998700,8.249140',
mode: 'fastest;car;traffic:enabled',
departure: 'now'};
router.calculateRoute(parameters,
function (result) {
console.log(result.response.route[0].summary.distance);
}, function (error) {
console.log("error");
});
}
So just call the calculateRoute() function inside the geocoder.geocode() function (pass the lat and long with it) and only then you can use the latitude and longitude within the calculateRoute() function to calculate the distance.
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'm trying to make a page that will use the openweathermap api to display the user's city and local temperature, unfortunately it doesn't seem to be processing the JSON api and is doing nothing. My code is fine as far as I can tell so I don't understand what's wrong.
Here's the jsfiddle link and javscript code: https://jsfiddle.net/qo2h1L9e/2/
$(document).ready(function() {
var data;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
console.log(lat);
console.log(lon);
console.log("api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&APPID=4907e373098f091c293b36b92d8f0886");
$.getJSON("api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&APPID=4907e373098f091c293b36b92d8f0886", function(json) {
data = json;
console.log(data.name);
$("#city").text(data.name);
});
});
}
});
I had a similar issue when coding this. Assuming you're on FCC?
Anyways, try adding &callback=? to the api URL. You may need to get the data as JSONP rather than JSON.
Also, you don't need to define data. You could access the object directly through the json parameter.
I have done it jQuery try this code
$(document).ready(function() {
var data;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
console.log(lat);
console.log(lon);
console.log("api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&APPID=4907e373098f091c293b36b92d8f0886");
// $.getJSON("api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&APPID=4907e373098f091c293b36b92d8f0886", function(json) {
// data = json;
// console.log(data.name);
// $("#city").text(data.name);
// });
var url = 'http://api.openweathermap.org/data/2.5/weather';
var params = {};
params.lat = lat;
params.lon = lon;
params.APPID = "4907e373098f091c293b36b92d8f0886";
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
contentType: "application/json; charset=utf-8",
data: params,
success: function (res) {
console.log(res);
},
error: function (res) {
}
});
}
);
}
});
The problem is in json.For cross domain use jsonp.
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.
There's a small issue that i'm facing.
Part 1:
A little insight on what i'm trying to do.
Window.onload [in javascript] calls a function which displays the googlemaps nothing else.
Then on click of a button the latitude & longitude are read from the MySQL database, this code is written in C# code behind.
And from C# i call a javascript function with those latitude & longitude as parameters.
Now the javascript function Should place a marker on the received parameters, instead it reloads the googlemap and i don't see any Marker!
Part 2: I want to call a javascript again and again from a while loop to send the latest latitude and longitude as long as there is data in the MySQL table.
//The While Loop reads a row, and calls the javascript function !But for some reason the Javascript function gets called only once.
while(read.Read())
{
id= read["ID"].ToString();
lat = read["latitude"].ToString();
longitude = read["longitude"].ToString();
freq=read["frequency"].ToString();
array_ID.Add(Convert.ToInt32(id));
array_lat.Add(Convert.ToDouble(lat));
array_lon.Add(Convert.ToDouble(longitude));
array_freq.Add(Convert.ToInt32(freq));
string[] myarr = { id, lat, longitude, freq };
javascriptfunction_markers(myarr);
}
public void javascriptfunction_markers(string[] myarray_data)
{
StringBuilder javascriptFunction = new StringBuilder();
javascriptFunction.Append("qasim(");
javascriptFunction.Append("'" + myarray_data[0].ToString() + "',");
javascriptFunction.Append("'" + myarray_data[1].ToString() + "',");
javascriptFunction.Append("'" + myarray_data[2].ToString()+ "',");
javascriptFunction.Append("'" + myarray_data[3].ToString()+ "');");
Page.ClientScript.RegisterStartupScript(Page.GetType(), "OnLoadCall", javascriptFunction.ToString(), true);
}
the string built here looks like on a sample data :
qasim('1','33.2358','72.4560',5);
the javascript function 'qasim' in .aspx is :
function qasim(id,lat,lon,freq)
{
var ltlngx = [];
var x = id.toString();
var x1 = lat.toString();
var x2 = lon.toString();
var x3 = freq.toString();
alert("Function ID : " + x +" Lat: "+ x1 + " Lon: " + x2 +"Freq: "+ x3);
count = count + 1;
alert("Called times " + count.toString());
var xx = parseFloat(lat);
var yy = parseFloat(lon);
ltlngx.push(new google.maps.LatLng(xx, yy));
alert("Lat,lng is " + ltlngx[0]);
map.setCenter(ltlngx[0]);
marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: ltlngx[0],
icon: 'images/map-pin.png'
});
var i=0;
(function (i, marker) {
var xx = marker.position.toString();
google.maps.event.addListener(marker, 'click', function () {
if (!infowindow) {
infowindow = new google.maps.InfoWindow();
}
infowindow.setContent('Location info:<br/><br/>Lat & Lng:' + xx + "<br/>" + " ID : "+x+" Freq: "+x3);
infowindow.open(map, marker);
});
})(i, marker);
}