0

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 + '&deg;F / '+ weather.alt.temp +'&deg;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.

HCL
  • 1
  • 3
  • Can you post a sample of the geolocation data? I.e the `geolocation` property of `navigator` – Tony M Apr 18 '17 at 22:44
  • This is daft but how would I do so? – HCL Apr 19 '17 at 01:00
  • `console.log(navigator.geolocation);` should log that data to the console. The idea is to see exactly what type of data it is so that you know what to request from users on (for example) an input field (or a combination of fields). – Tony M Apr 19 '17 at 03:19
  • Didn't seem to work when I used console.log, but I tried document.write and got this"[object Geolocation]" – HCL Apr 19 '17 at 17:07

1 Answers1

0

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.

Tony M
  • 741
  • 4
  • 16
  • Hmm, I tried that with the Google Maps API but it seems that nothing is actually happening when I manually enter an address... Not too sure what's going on there – HCL Apr 19 '17 at 19:22
  • Is the API returning coordinates? At minimum I'd ensure that it is doing so. The fiddle I have here works: https://jsfiddle.net/7u539rfq/11/ Notice how the values appended to the `div` are coordinates. Those are the values you feed your `loadWeather(arg1,arg2)` function. To test, my input was "Portland, Oregon" – Tony M Apr 19 '17 at 19:56
  • Weirdly nothing comes up as a console.log, and I tried document.write() as well but nothing is parsing. I've tried it on your fiddle with success, so I have no idea what could be going wrong on my end :/ – HCL Apr 19 '17 at 20:17
  • https://jsfiddle.net/mjsgwq55/2/ updated it. You're missing a few things: Jquery library, `$` definition and you are still missing the Yahoo Weather API (at least on the fiddle), so add that. At the moment you'll get an error that `$.simpleWeather` isn't defined - because it isn't. Either post the Yahoo API details or simply use what's in that fiddle, should work. – Tony M Apr 19 '17 at 21:36
  • I've updated my answer @HCL . The fiddle works now (got the API endpoint). Let me know if this solves your issue and mark the answer if correct, cheers! – Tony M Apr 19 '17 at 21:49
  • Just to clarify, weatherText is a var that corresponds to an array of strings that appear in the .weather-text div, not sure if that's relevant. It's still not updating, but it works on your fiddle. I'm using the simpleweather.js plugin as you probably already now, but I'm not sure what else I'm missing. ` ` – HCL Apr 19 '17 at 23:49
  • Try this link for simpleWeather: https://cdnjs.cloudflare.com/ajax/libs/jquery.simpleWeather/3.1.0/jquery.simpleWeather.min.js Just click to open and copy the url. Make sure it actually loads the minified JS. Your link is broken because somehow you have spaces between characters. To see what I mean, copy the simpleWeather src from your script tag (the link) and paste it on a text editor. – Tony M Apr 20 '17 at 03:09
  • I was really hoping that was it.. But I think the space appeared when I pasted the code snippet above. Here's my git repo if this helps - https://github.com/cuiiii/the-weather-in-words Thank you so much for sticking with me through this, I've been pulling my hair out!! – HCL Apr 20 '17 at 05:11
  • It's usually the tiniest detail. And no worries, just a sec. – Tony M Apr 20 '17 at 16:46
  • Having some problems pushing. Anyway, the problem was that you were appending the `input` and `button` tags within the `simpleWeather` function. When the `click` event is fired, the function hasn't been called yet and the button doesn't exist. So either add them on `document.ready` or just put them in the index.html as I did. – Tony M Apr 20 '17 at 17:02
  • It works! I have it in document.ready but it's still loading before the weather `(function($){ $(document).ready(function(){ if ("geolocation" in navigator) { navigator.geolocation.getCurrentPosition(function(position) { loadWeather(position.coords.latitude + ',' + position.coords.longitude); }); $(".weather-input").html(''); $(".weather-input").append(''); } else { $(".weather-text").html("Aw, geolocation isn't supported by this browser."); }` – HCL Apr 20 '17 at 17:30
  • Ahh I see. It's always good practice to leave markup on the .html file. Glad it works though:) Feel free to mark answer as correct (as at is:) – Tony M Apr 20 '17 at 17:48