EDIT: Just finished up the project. New link is up here! http://codepen.io/myleschuahiock/full/pyoZge/
I'm in the process of making a Weather Widget App for my Free Code Camp. Everything except the "city" is a static placeholder. I'm using the Open Weather Api, which makes us to a latitude and longitude. For debugging purposes, I placed the longitude and latitude of my area underneath the time placeholder.
My problem is that when I statically input the lat and lon on my API link, it works just fine. It returns "Mandaluyong City", a nearby city where I live:
http://api.openweathermap.org/data/2.5/weather?lat=14.603814400000001&lon=121.04907589999999&id=524901&APPID=ca8c2c7970a09dc296d9b3cfc4d06940
But when I do this, where I dynamically add mylatitude and mylongitude, to complete the API link:
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + mylatitude + "&lon=" + mylongitude + "&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
I always get "Moscow" as my city.
Please take a closer look at my Javascript/JQuery code here!
http://codepen.io/myleschuahiock/pen/zqYzWm?editors=0010
Thank you very much! Much appreciated!
Easy solution for you.
Move the $.getJSON() into your if condition, why attempt to query the weather if the client blocks the location?
As Jaromanda X has pointed out:
navigator.geolocation.getCurrentPosition is asynchronous. So, you're calling $.getJSON before the location is actually determined.
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$('.geo').html(position.coords.latitude+ " " +position.coords.longitude);
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat="+position.coords.latitude+"&lon="+position.coords.longitude+"&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
});
});
}else{
$(".geo").html("Please turn on Geolocator on Browser.")
}
});
I hope this helps. Happy coding!
Added
getName(mylatitude, mylongitude);
and changed
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + mylatitude + "&lon=" + mylongitude + "&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
});
to
function getName(mylatitude, mylongitude){
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + mylatitude + "&lon=" + mylongitude + "&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
});
}
http://codepen.io/anon/pen/Yqzvbd?editors=0010
You can use third-party IP API that provides the name of the city. With use jQuery function $.getJSON()
var openWeatherMap = 'http://api.openweathermap.org/data/2.5/weather';
var APPID = 'APPID';
var ipAPI = 'http://ip-api.com/json/';
$.getJSON(ipAPI).done(function(location) {
$('.geo').html(location.lat + " " + location.lon);
$('.city').html(location.city);
$.getJSON(openWeatherMap, {
lat: location.lat,
lon: location.lon,
APPID: APPID
}).done(function(weather) {
$('#temperature').html(weather.main.temp - 273.15);
})
})
OpenWeatherMap provides the temperature in Kelvin on this I did weather.main.temp - 273.15 to get Celsius
Related
Im trying to display my location on my web app, it shows my coordinate correctly, but when i try to employ google geocoding, it keeps showing 400(bad request) in the console.
$("#location-button").click(function() {
// document.getElementById('#location-button').click(function(){
if(navigator.geolocation)
navigator.geolocation.getCurrentPosition(function(position){
console.log(position);
$.get("http://maps.googleapis.com/maps/api/geocode/json?latlng="+ position.coords.latitude + "," + position.coords.longitude + "?key= "+"AIzaSyD3rQONJZostxOofIY9ZfaAsta-fqf1nBbs" + "&sensor=false", function(data) {
// $.get("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "?key= "+"AIzaSyD3rQONJZostxOofIY9ZfAsta-fqf1nBbs" + "&sensor=false", function(data) {
console.log(data);
})
Please note im not good with javascript, i just want to use this bits
I want to get the the users current location address(city, street etc) on click event.
I have tried html5 geolocation and tried to console the data. on button click i am checking geo location is supported by creating alert box, and its executes succesfully, But its not printing any values in the console.
HTML
<div id="navbar"><span> Geolocation API</span></div>
<div id="wrapper">
<button id="location-button">Get User Location</button>
<div id="output"></div>
My script
<script>
$('#location-button').click(function(){
if (navigator.geolocation) {
alert("it is supported");
navigator.geolocation.getCurrentPosition(function(position){
console.log(position);
$.get( "http://maps.googleapis.com/maps/api/geocode/json?latlng="+ position.coords.latitude + "," + position.coords.longitude +"&sensor=false", function(data) {
console.log(data);
})
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + position.coords.latitude + "," + position.coords.longitude + "&zoom=13&size=800x400&sensor=false";
$('#output').html(img);
});
}
else
{
console.log("geo location is not supported")
}
});
</script>
I want to get the full address of the users location.
You may visit this jsfiddle sample that demonstrates your use case.
Kindly note that it is not recommended to use web service in the client side, as web service requests are recommended to be used for server side requests.
As you can see below, what I used is a Geocoder Service instead of the Web Service Geocoding
geocoder.geocode( { 'location': pos}, function(results, status, infowindow) {
if (status == 'OK') {
console.log(results[0].formatted_address);
infoWindow.setContent('Location found: '+ results[0].formatted_address);
infoWindow.setPosition(pos);
infoWindow.open(map);
} else {
console.log('Geocode was not successful for the following reason: ' + status);
}
});
you simply can't! Geolocation use triangulation or GPS from the mobile and you'll get get longitude and latitude values or even the IP and you'll get nearest distributor device(haven't right word in english).
Obviously for geolocation the user have to authorize it too.
So if you want address the simpliest is to ask by a form. You can use a map related with longit/latitude matching but it'll be a pain and waste to do because you've to use all maps and places on earth related to use it that way.
I'm building a web-page that shows the weather. I would like for it to be able to use geolocation, as well as the option to manually input a location to pull weather information. I've got the geolocation working fine, but am unsure as to how to add an additional input using either a city or zipcode.
Here's my relevant code:
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(function(position) {
loadWeather(position.coords.latitude + ',' + position.coords.longitude);
});
} else {
loadWeather("", "1062617");
}
function loadWeather(location, woeid) {
$.simpleWeather({
location: location,
woeid: woeid,
unit: 'f',
success: function(weather) {
$(".weather-text").html(weatherText[weather.code]);
$(".weather-icon").html('<i class="icon-' + weather.code + '"></i>');
$(".weather-stats").html('<ul><li><strong>'+weather.city+', ' +weather.region+ '</strong></li>');
$(".weather-stats").append('<li>'+ weather.temp + '°F / '+ weather.alt.temp +'°C</li></ul>');
},
error: function(error) {
$("#weather").html('<p>' + error + '</p>');
}
});
}
I'm pretty new to javascript & jquery, so I understand how to make an input box with HTML but am unsure how to use the user input data to then retrieve the associated weather data.
The getCurrentPosition gives you access to the position interface which then gives you the coordinates. So your if statement results in a latitude and longitude based on the device's Geolocation. In order to get this same information from a user's input (latitude and longitude), you need to convert the input (could be City, State or a full address) to coordinates. I recommend using Google maps API to convert that user input.
Once converted, you can then pass the lat and long to loadWeather(). Here's an example of a user's input (Address) converted:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
var address = jQuery('#address').val();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
jQuery('#coordinates').val(latitude+', '+longitude);
loadWeather(latitude + ',' + longitude);
}
});
</script>
<input id="address" type="text" placeholder="Enter City, State"/>
Of course you would use the above within proper context such as checking whether geolocation worked first or whenever a user actually enters their address. You might need a Google Maps API for this bit that should be easy to get.
Give it a shot, if stuck, check out this fiddle: jsfiddle
EDIT:
I grabbed Yahoo's Weather API endpoint and here is working fiddle:
https://jsfiddle.net/mjsgwq55/3/
I highly recommend logging variables so you can tell what time of data they contain. In your fiddle, you tried to access a property that doesn't exist in the object. Logging that would easily show you what to use.
I'm developing a mobile web application with Spring MVC. For geolocation, I get the code from here
I ran the demo from my phone on that site and it's asking for location permission, same thing on jsfiddle demo, and it's working. If I don't have Gps enable I get '"Unable to retrieve your location'.
But on my application, I get instantly the above message, without asking for permission(also, removed all blocked apps from chrome).
On PC, geolocation is working,through my app, but on my phone, not.. What can be the problem?Meaning.. why geolocation is not working on my phone through my app, but it's working for other sites. On my phone, goes directly to error() function.
Maybe I have to make some changes in the configuration files,or I don't know..
LE: Tested on 2 more devices, same output:Unable to retrieve your location ... (GPS enabled)
LE2:I checked the error code. I'm getting permission denied
This is the Fiddle
<p><button onclick="geoFindMe()">Show my location</button></p>
<div id="out"></div>
//Javascript
function geoFindMe() {
var output = document.getElementById("out");
if (!navigator.geolocation){
output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
return;
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
output.appendChild(img);
};
function error() {
output.innerHTML = "Unable to retrieve your location";
};
output.innerHTML = "<p>Locating…</p>";
navigator.geolocation.getCurrentPosition(success, error);
}
You can check this code,
https://github.com/makubex88/MobileHTML5CodeCamp/blob/master/mobilehtml5.html
function showPosition(position) {
var latlon = position.coords.latitude + "," + position.coords.longitude;
var img_url = "http://maps.googleapis.com/maps/api/staticmap?center="+latlon+"&zoom=14&size=400x300&sensor=false";
document.getElementById("mapholder").innerHTML = "<img src='" + img_url + "'>";
}
I'm trying to get lng and lat coordinates of the Google Maps API by the next example http://jsbin.com/inepo3/7/edit. I expect a 'success' popup, but it keeps showing the 'Error' popup.
The google maps-request gives the correct json feedback (checked by firebug).
<script type="text/javascript">
$().ready(function() {
$.fn.getCoordinates=function(address){
$.ajax(
{
type : "GET",
url: "http://maps.google.com/maps/api/geocode/json",
dataType: "jsonp",
data: {
address: address,
sensor: "true"
},
success: function(data) {
set = data;
alert(set);
},
error : function() {
alert("Error.");
}
});
};
$().getCoordinates("Amsterdam, Netherlands");
});
</script>
Does anyone know how to fix this issue?
Regards,
Guido Lemmens
EDIT
I found a bether solution using the Google Maps Javascript API combined in jQuery:
<script type="text/javascript">
$().ready(function() {
var user1Location = "Amsterdam, Netherlands";
var geocoder = new google.maps.Geocoder();
//convert location into longitude and latitude
geocoder.geocode({
address: user1Location
}, function(locResult) {
console.log(locResult);
var lat1 = locResult[0].geometry.location.lat();
var lng1 = locResult[0].geometry.location.lng();
$("#testDiv").html("latitude:" + lat1 + "<p>longitude:" + lng1 + "</p>");
});
});
</script>
Google Map API V3 makes it harder for external libraries to work with JSONP. Here is a blog post about it.
JSONP and Google Maps API Geocoder Plus A Fix w/ jQuery
An alternative way of getting Geocoding is to use the Google Map V3 API Geocoder Service. Here is an example that i helped a person that was having a similar issue as you to replace his JSONP to use Google Map V3 Geocoder Service. Take a look at this JSFiddle Demo:
This is basically the core. We basically use twitter to get the tweet's address (IE. London, Madrid or Georgia etc) and convert the actual address into LatLng using Google Map's Geocoder Service:
$.getJSON(
url1, function(results) { // get the tweets
var res1 = results.results[0].text;
var user1name = results.results[0].from_user;
var user1Location = results.results[0].location;
// get the first tweet in the response and place it inside the div
$("#last-tweet1").html(res1 + "<p>from: " + user1name + " (" + user1Location + ")</p><p>");
//convert location into longitude and latitude
geocoder.geocode({
address: user1Location
}, function(locResult) {
console.log(locResult);
var lat1 = locResult[0].geometry.location.lat();
var lng1 = locResult[0].geometry.location.lng();
$("#testDiv").html("latitude:" + lat1 + "<p>longitude:" + lng1 + "</p>");
});
});