[英]HTML5 geolocation lat and long coordinates of current GPS position into a variable
I am trying to get the current latitude and longitude values of the user by utilising HTML5's geolocation functionality. 我试图通过利用HTML5的地理位置功能来获取用户的当前纬度和经度值。 After researching and trying to get an answer from other questions here on StackOverflow I seem to still be misunderstanding the concept of accessing a global variable. 在研究并尝试从StackOverflow上的其他问题中获得答案之后,我似乎仍然误解了访问全局变量的概念。 Everything I have seen so far makes it look like there is a issue with the scope. 到目前为止,我所看到的一切都使示波器看起来像有问题。 The code I am using looks like it is using a function within function. 我正在使用的代码看起来像是在函数中使用函数。 I am currently running the following code: 我当前正在运行以下代码:
<script type="text/javascript">
var currentLat = 0;
var currentLong = 0;
function getPosition() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position) {
console.log(position.coords.latitude);
console.log(position.coords.longitude);
}
getPosition();
This code currently works in the fact that it logs the information to the console. 当前,此代码的工作原理是将信息记录到控制台。 However if I change the code to this it doesn't seem to work: 但是,如果我将代码更改为此,则似乎不起作用:
<script type="text/javascript">
var currentLat = 0;
var currentLong = 0;
function getPosition() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position) {
currentLat = position.coords.latitude;
currentLong = position.coords.longitude;
}
getPosition();
console.log(currentLat + "," + currentLong);
It just returns 0 like I set originally. 就像我最初设置的那样,它只会返回0。 I have searched a lot on global variables but most of the resources online (including StackOverflow) state that I can access these variables as long as I don't redeclare the variable inside a function (or creating a local scope variable that overrides the global variable). 我在全局变量上进行了大量搜索,但是大多数在线资源(包括StackOverflow)都指出,只要不在函数内部重新声明变量(或创建覆盖全局变量的局部范围变量),就可以访问这些变量。 )。
Thanks to gro's comment I found this works: 感谢gro的评论,我发现这行得通:
window.onload = function(){
navigator.geolocation.getCurrentPosition(function(position) {
window.currentLat = position.coords.latitude;
window.currentLong = position.coords.longitude;
window.currentLatLong = new google.maps.LatLng(currentLat,currentLong);
init();
});
}
function init() {
// run code here and reference currentLatLong, currentLat and currentLong
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.