javascriptjqueryajaxlocationcoords

Get position coordinates for an ajax request


Currently working on a weather web-app for iOS. I'm trying to get the coordinates of the user and put the latitude and longitude in my Ajax request (on the api Wunderground) .

Here's my code (EDIT):

<script type="text/javascript">
       $(document).ready(function() {

       navigator.geolocation.getCurrentPosition(getLocation, unknownLocation);

         function getLocation(pos)
         {
           var lat = pos.coords.latitude;
           var lon = pos.coords.longitude;

            $.ajax({
                     url : "http://api.wunderground.com/api/ApiId/geolookup/conditions/q/"+ lat +","+ lon +".json",
                     dataType : "jsonp",

                     success : function(parsed_json) {
                        var location = parsed_json['location']['city'];
                        var temp_f = parsed_json['current_observation']['temp_f'];
                        alert("Current temperature in " + location + " is: " + temp_f);
                     }
                  });
         }
         function unknownLocation()
         {
           alert('Could not find location');
         }
       });
    </script>

As you can see I "simply" have to create 2 vars lat and lon and add them in my request. I tried a lot of variants but I can't get this code working.

Any idea of what I'm doing wrong ?

Thank you very much !


Solution

  • Your variable declarations are in the middle of the .ajax call, and are making the JavaScript structure invalid. Also, I'm not sure why you're using "function($)", normally with jQuery the $ is reserved and shouldn't be used as a function parameter.

       <script type="text/javascript">
    $(document).ready(function() {
        navigator.geolocation.getCurrentPosition(onPositionUpdate);
    });
    
    
    function onPositionUpdate(position) {
        var lat = position.coords.latitude;
        var lon = position.coords.longitude;
        $.ajax({
            url : "http://api.wunderground.com/api/ApiId/geolookup/conditions/q/"+lat+","+lon+".json",
            dataType : "jsonp",
            success : function(parsed_json) {
                var location = parsed_json['location']['city'];
                var temp_f = parsed_json['current_observation']['temp_f'];
                alert("Current temperature in " + location + " is: " + temp_f);
            }
        });
    }
    </script>