Location and weather based image search API for weather app - javascript

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.

Related

How could I implement weather forecast based on geolocation using Open Weather Map?

In my website there are 2 buttons and a search bar. If you enter a city name there and press one of the 2 buttons, you' ll get the forecast of that city. If you press the other one, you'll get the coordinates of your position. I just want to remove the coordinates and get the weather forecast even when you press the geolocation button. I've tried a lot, but I'm not good enough.
I need Open Weather Map APIs to be used.
Thanks to all those who will help me.
I attach al the JS code below.
function getWeather () {
$('.weatherResponse').html('');
var cityName = $('#cityName').val();
var apiCall=
'http://api.openweathermap.org/data/2.5/weather?q=' + cityName +
'&appid=02b664040367b84ac7ae1334618923fd'
;
$.getJSON(apiCall, weatherCallback);
function weatherCallback(weatherData) {
var cityName = weatherData.name;
var country = weatherData.sys.country;
var temp=
weatherData.main.temp;
temp = parseInt(temp) - 273;
var description=
weatherData.weather[0].description;
var iconcode=
weatherData.weather[0].icon;
var iconurl = "http://openweathermap.org/img/wn/" + iconcode + "#2x.png";
$('.weatherResponse').append("The weather in " + cityName + " " + country + " is currently " + description + " and it' s " + temp + "°");
document.getElementById('wicon').style.display='inline';
$('#wicon').attr('src', iconurl);
}
}
function GeoFind()
{
var out = document.getElementById("out");
if (!navigator.geolocation) {
out.innerHTML = "<p> Geolocation is not supported in your browser </p>";
return;
}
var geo_options = {
enableHeightAccuracy: true,
maximumAge: 30000,
timeout: 27000,
}
function geo_success(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
out.innerHTML = "<p> Latitude is "+ lat +" ° <br>Longitude is "+ long +" ° </p>";
}
function geo_error () {
out.innerHTML = "Unable to retrieve your location!";
}
out.innerHTML = "<p> Locating... </p>";
navigator.geolocation.getCurrentPosition(geo_success, geo_error, geo_options);
}

Undefined Value When Converting Metrics

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);

OpenWeatherMap API - Trouble with append longitude and latitude

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);

Why markers do not move correcly on map

Sample of JSON data (from the comments):
[{"id":"280","id_vehicle":"VL0847810531","lat":"30.0761","longi":"1.01981","spee‌​d":"144","time":"2014-12-03 12:07:23"},{"id":"202","id_vehicle":"VL0645210631","lat":"34.7344","longi":"7.32‌​019","speed":"78","time":"2014-12-03 11:55:44"}]
function updateLocations(jsonData)
{
for (i=0 ;i< jsonData.length; i++) //for all vehicles
{
var id_vehicle = jsonData[i]["id_vehicle"];
var lat = jsonData[i]["lat"];
var lng = jsonData[i]["longi"];
var speed = jsonData[i]["speed"];
var str_time = jsonData[i]["time"];
/************************update list*******************************/
var state_icon, marker_icon, state;
var time = moment(str_time);
var last_10_Min = moment().subtract({minutes: 60 + 10});
if(time.isBefore(last_10_Min)) //if before 10 last minutes
{
state_icon = INACTIVE_IMG;
marker_icon = INACTIVE_VEHICLE;
state = "INACTIVE";
}
else //if befor
{
if(jsonData[i]["speed"] > 10) //if > 2 km/h then running
{
state_icon = RUN_IMG;
marker_icon = RUN_VEHICLE;
state = "RUN";
}
else
{
state_icon = STOP_IMG;
marker_icon = STOP_VEHICLE;
state = "STOP";
}
}
$("#state_img_"+id_vehicle).attr("src", state_icon);
$("#state_img_"+id_vehicle).attr('state',state);
$("#select_"+id_vehicle).attr("disabled" , false ); // enable selection
/************************update location info*******************************/
var locationInfo = new Array();
img = "<img src=" + state_icon + " width='16' height='16' >";
locationInfo.push("Etat : " + state + " " + img + "<br>");
locationInfo.push("Latitude : " + lat + "<br>");
locationInfo.push("Longitude : " + lng + "<br>");
locationInfo.push("Vitess: " + speed + " klm/h<br>");
locationInfo.push("Temps : " + str_time + "<br>");
$("#info_location_" +id_vehicle).html(locationInfo.join(""));
/*****************update vehicles on map *************/
try {
cBox = $("#select_"+id_vehicle);
if(cBox.is(':checked')) //update selected only
{
//get marker index
var id_map = cBox.attr("id_map");
//change title
title = "Latitude: "+ lat + "\nLongitude: " + lng + "\nSpeed: " + speed + "\nTime: " + str_time;
arrayMarker[id_map].setTitle(title); //update title
arrayMarker[id_map].setIcon(marker_icon);
//move marker
arrayMarker[id_map].setPosition( new google.maps.LatLng(parseFloat(lat),parseFloat(lng)) );
}
}catch(error){};
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
my question is why whene this function is executed (updating locations) just fisrt vehicle on map is moved correctly, the ohers are updated (title, icon ...) but do not move?
I noticed that , they move and return to their old location quickly.
Thanks for any suggestion.
finaly i found problem, it was here:
var marker = new MarkerWithLabel({......});
arrayMarker[id_map] = marker; //put marker in arrayMarker at indexMarker position
the bug occur whene i filled my arrayMarker using MarkerWithLabel (3th lib)
whene changed to native google.maps.Marker it work correcly:
var marker = new google.maps.Marker({......});
arrayMarker[id_map] = marker;

How to change google maps marker icon dynamically

I am using ajax and php and I grabbing all of the points out of my database and plotting them on the map. Which works fine. However I want to change the icon of the marker depending on if status in the database is 100 or 200 or 300 for each record. I can't seem to get anything to work. Here is my code:
if (localStorage.getItem('type2') !== null) {
$(function ()
{
var radius2 = localStorage.getItem("radius2");
var lat2 = localStorage.getItem("lat2");
var long2 = localStorage.getItem("long2");
var type2 = localStorage.getItem("type2");
var city2 = localStorage.getItem("city2");
var rep2 = localStorage.getItem("rep2");
var size2 = localStorage.getItem("size2");
var status2 = localStorage.getItem("status2");
$.ajax({
url: 'http://example.com/Test/www/22233333.php',
data: "city2=" + city2 + "&rep2=" + rep2 + "&status2=" + status2 + "&size2=" + size2 + "&type2=" + type2 + "&long2=" + long2 + "&lat2=" + lat2 + "&radius2=" + radius2,
type: 'post',
dataType: 'json',
success: function (data) {
$.each(data, function (key, val) {
var lng = val['lng'];
var lat = val['lat'];
var id = val['id'];
var name = val['name'];
var address = val['address'];
var category = val['category'];
var city = val['city'];
var state = val['state'];
var rep = val['rep'];
var status = val['status'];
var size = val['size'];
$('div#google-map').gmap('addMarker', {
'position': new google.maps.LatLng(lat, lng),
'bounds': true,
'icon': 'images/hospital.png'
}).click(function () {
$('div#google-map').gmap('openInfoWindow', {
'backgroundColor': "rgb(32,32,32)",
'content': "<table><tr><td>Name:</td><td>" + name + "</td></tr><tr><td>Address:</td><td>" + address + ", " + city + " " + state + "</td></tr><tr><td>Category:</td><td>" + category + "</td></tr><tr><td>Rep:</td><td>" + rep + "</td></tr><tr><td>Status:</td><td>" + status + "</td></tr><tr><td>Size:</td><td>" + size + "</td></tr></table>"
}, this);
});
})
}
});
})
}
Looks like you are using jquery-ui-map?
I haven't used this abstraction
You can call the setIcon function - on a marker you can set it's icon this way for the main API
https://developers.google.com/maps/documentation/javascript/reference#Marker
So your addMarker method will return a marker instance by the look of it so once you have that run setIcon
Do something like this in your success function with in $.each.
Status is the database field
var size = val['size'];
var status = val['status'];
var icon = '';
if (status == 100){
icon = 'images/icon1.png'; //your icon1
}else if (status == 100){
icon = 'images/icon1.png'; //your icon2
}
...
$('div#google-map').gmap('addMarker', {
'position': new google.maps.LatLng(lat, lng),
'bounds': true,
'icon': icon //your dynamic icon
})
Hope this helps

Categories

Resources