javascript - Current coordinates returns undefined -
javascript - Current coordinates returns undefined -
this question has reply here:
why variable unaltered after modify within of function? - asynchronous code reference 6 answersi'm trying utilize getlocation function current location coordinates , utilize distance calculation in future. after run next code, got undefined.
<script type="text/javascript"> var currentlatitude; var currentlongitude; function getlocation() { if (navigator.geolocation) { navigator.geolocation.getcurrentposition(getcoordinates); } else { document.getelementbyid("asdfsdafsdaf").innerhtml = "geolocation not supported browser."; } } function getcoordinates(position) { currentlatitude = position.coords.latitude; currentlongitude = position.coords.longitude; } var xhr = new xmlhttprequest(); xhr.open("post", "rsvpbutton.php", true); var formdata = new formdata(); formdata.append("userid", 100100); xhr.send(formdata); xhr.onload=function(){ getlocation(); alert("1"+currentlongitude+" , "+currentlatitude); //some other codes display page //... } </script>
i thought set 2 vars in wrong places after tried several times still not work. help please? in advance.
updates: tried set bottom codes callback function, whole page disappeared.
getcurrentposition
accepts callback, it's asynchronous. read more here: https://developer.mozilla.org/en-us/docs/web/api/geolocation.getcurrentposition
try putting alert
in callback instead:
<script type="text/javascript"> var currentlatitude; var currentlongitude; function getlocation(callback) { if (navigator.geolocation) { navigator.geolocation.getcurrentposition(callback); } else { document.getelementbyid("asdfsdafsdaf").innerhtml = "geolocation not supported browser."; } } var xhr = new xmlhttprequest(); xhr.open("post", "rsvpbutton.php", true); var formdata = new formdata(); formdata.append("userid", 100100); xhr.send(formdata); xhr.onload=function(){ getlocation(function (position) { var currentlatitude = position.coords.latitude; var currentlongitude = position.coords.longitude; alert("1"+currentlongitude+" , "+currentlatitude); //some other codes display page //... }); } </script>
javascript
Comments
Post a Comment