0

I am making a request to an app that I'm running on another server. I know my browser supports geolocation, because I've tried it elsewhere. Here is what I currently have:

<script>
    function getLocation(){
        if(navigator.geolocation){
            navigator.geolocation.getCurrentPosition(showPosition)
        }else{
            console.log("Geolocation is not supported");
        }
    }
    function showPosition(position){
        return position.coords.latitude+" "+position.coords.longitude;
    }

    (function () {
        var latlong = getLocation();
        console.log("Latlong " + latlong);
        var http = new XMLHttpRequest();
        http.open("POST", "http://api.example.com/", true);
        http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        var params = "location=" + latlong;
        http.send(params);
        http.onload = function() {
            alert(http.responseText);
        }
    })();
</script>

The request works, but the location param is set to undefined. Why is it not defined?

jordan
  • 9,570
  • 9
  • 43
  • 78

2 Answers2

1

Function getCurrentPosition accepts three parameters like this.
navigator.geolocation.getCurrentPosition(success, error, options);

Simply put your output function needs to be in success.

Working fiddle

JTC
  • 3,344
  • 3
  • 28
  • 46
0

Move the Ajax request into the showPosition callback. At the moment you call params before it is filled.

localghost
  • 142
  • 5