Grabbing longitude and Latitude value from a function

岁酱吖の 提交于 2019-12-31 05:24:05

问题


Please how do i get the value of "lat" and "lon" outside their function to use else where on the page.

   navigator.geolocation.getCurrentPosition(handle_geolocation_query,handle_errors);  

    function handle_errors(error)  
    {  
        switch(error.code)  
        {  
            case error.PERMISSION_DENIED: alert("user did not share geolocation data");  
            break;  
            case error.POSITION_UNAVAILABLE: alert("could not detect current position");  
            break;  
            case error.TIMEOUT: alert("retrieving position timed out");  
            break;  
            default: alert("unknown error");  
            break;  
        }  
    }  
   function handle_geolocation_query(position){  
        var lat = (position.coords.latitude);
       var lon = (position.coords.longitude); 

    }

What i am trying to do is to get the longitude and latitude of a device and pass it is as a parameter to query and database, also use that same value for other things. I cant figure out how to go about it. Any help will be much appreciated.


回答1:


The first thing came my mind (at this late hour :D) is something like this:

  • declare a variable outside your handlers, let's say:

    var coords = {};

  • then in your 'handle_geolocation_query' handler, trigger an event that gives you an ideea that your position is ready, assuming you're using jQuery:

    $(coords).trigger('positionReady', position);

  • after that, everywhere you need those coordinates, listen for your custom 'positionReady' event, and do your job:

    $(coords).on('positionReady', function(e, position) { console.log(position); });

This will help you to avoid 'spaghetti code', but in the same time, you need to 'think' asynchronously, and maybe using callbacks the (right) way you need.



来源:https://stackoverflow.com/questions/18883252/grabbing-longitude-and-latitude-value-from-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!