Search code examples
jqueryhtmlajaxjsongeolocation

HTML5 Geolocation - Replace/Add Data to Ajax URL string


So I'm trying to get the users location and then replace the position coords into the json URL request for latitude and longitude using jQuery and then outputing it to an ElementByID on the page.

Below is what I've come up with, but it doesn't seem to be working. Instead of replacing the string it outputs as http://api.wunderground.com/api/My-API-key/geolookup/conditions/q/+position.coords.latitude+,+position.coords.longitude+.json

Below is the code,

<a id="demo"></a>

<script>
    var x = document.getElementById("demo");


    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }


jQuery(document).ready(function showPosition(position) {
  $.ajax({
  url : "http://api.wunderground.com/api/MY-API-KEY/geolookup/conditions/q/" + position.coords.latitude + "/" + position.coords.longitude + ".json",
  dataType : "jsonp",
  success : function(parsed_json) {
  var location = parsed_json['location']['city'];
  var temp_f = parsed_json['current_observation']['temp_f'];
    x.innerHTML = location + temp_f
  }
  });
});


</script>

I'm using HTML5 Geolocation feature to get the location and then I try to replace the ajax URL adding the location data at the end to output the correct temperature, but for some reason it doesn't seem to work.

Any ideas, and tips would be awesome!


Solution

  • Okay, I figured it out. Below is the answer. The problem was I was trying to replace the end URL with a variable that was in another function. I simply needed to include the json request within the proper function for it read/access the variable.

    I feel dumb that I didn't see it before. Haha

    <a id="demo"></a>
    
    <script>
        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/MY-API-KEY/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;
      }
      });
    });
       }   
    
    </script>