开发者

Set data inside getCurrentPosition function

I'm doing next:

First thing - I'm checking if I already have loaded latitude and longitude data. If I do have, I'm saving that into array named "location".

Second thing - if I don't have any loaded data, I'm trying to get current position. After that, I'm trying to save latitude and longitude for current position. And, at the end, I'm calling setMap(); function where I check location array and where I'm generating a map.

Problem:

Well, as I said it...inside "getCurrentPosition", I'm trying to set current position into "location" array, and after that I'm trying to take those values inside setMap(); function. Here's the problem, but only when i set "location" values inside "getCurrentPosition". If I set "location" values manually before (from "data" array), everything works fine. Also, when I call a setMap() function inside "getCurrentPosition", everything works fine...but when I call it from outside, won't work. Can someone explain me what's going on and what can I do?

Here's my code:

location = new Array();
if (data.lat) {
        location['la开发者_开发知识库t'] = data.lat;
        location['lng'] = data.lng;
    } else {
        if (!navigator.geolocation) {
            //
        } else {        
            navigator.geolocation.getCurrentPosition(function(position) {
                location['lat'] = position.coords.latitude;
                location['lng'] = position.coords.longitude;
            });
        }       
    }
setMap();

Thank you.


You are setting a different variable inside of getCurrentPosition. I would suggest researching variable scope. Check out this question.

--edit--

I did not realize that the function you were using was a part of Javascript, I thought you had written/gotten it from somewhere.

Also, I stand corrected about the scope. Since you are using an array, the scope is fine, you should be able to set it inside the callback function just fine.

I ran your code and got some strange printouts when I did a console.log on location. I took a guess, and it appears that location is a reserved word. I bet that if you change the name of location to something else, your code should work fine.

--edit--

I should have realized this sooner actually, since location is the same as window.location, which is the browser bar location!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜