jordan
jordan

Reputation: 10812

Geolocation script not working

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?

Upvotes: 0

Views: 813

Answers (2)

localghost
localghost

Reputation: 142

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

Upvotes: 0

JTC
JTC

Reputation: 3464

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

Upvotes: 1

Related Questions