无法使用Geolocations API在JS Codepen中的函数之间传递var

时间:2017-10-21 14:56:11

标签: javascript jquery google-geolocation

我在CodePen上的JS代码中的函数之间传递url变量时遇到了麻烦:

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

function success(pos) {
  var crd = pos.coords;
  var lat = crd.latitude;
  var long = crd.longitude;
  var JSONurl = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + long + "&key=MY_APIKEY";

  console.log(JSONurl);
  console.log(`Latitude : ${crd.latitude}`);
  console.log(`Longitude: ${crd.longitude}`);
  return JSONurl;
 };

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
};

function getCity() {

  $.getJSON( JSONurl, function( json ) {
  var arr = $.map(json, function(el) { return el; })

  // console.log(Object.keys(arr[3]));
  console.log(arr[3]["address_components"][1]["long_name"]);

  }
)};


var JSONurl = navigator.geolocation.getCurrentPosition(success, error, options);             
getCity(JSONurl);

理想情况下,我想调用getCity()函数,并为该函数调用success(pos)函数,并启动并将JSONurl变量返回getCity()

我不知道为什么这不起作用,但无论如何它都有点黑客,所以欢迎任何改进建议。

1 个答案:

答案 0 :(得分:1)

  

所以有几个问题:

     
      
  1. navigator.geolocation.getCurrentPosition(success,error,options)不返回值。因此,“返回JSONurl”永远不会奏效。
  2.   
  3. key = MY_APIKEY应该是您的googleapis密钥(https://developers.google.com/maps/documentation/javascript/get-api-key,如果还没有)
  4.   
  5. 您需要使用承诺,因为您不知道googleapis何时会返回信息。
  6.   
  7. 由于上述原因,您可能不得不使用回调函数。
  8.   
  9. 如果API拒绝请求,您需要考虑。
  10.   

Working verison jsfiddle - 会提示输入google api密钥

(function(window){

  // Declare internal variables
  var _jsonURL = "";
  var _coords =  "";
  var _latitude =  "";
  var _longitude =  "";

  // Enter your google api key when prompted
  // https://developers.google.com/maps/documentation/javascript/get-api-key
  var APIKEY = prompt("Please enter your google API key ", ""); ; 

  // Create promise
  var _def = $.Deferred();

  window.GoogleAPI = {      
     options : {
                enableHighAccuracy: true,
                timeout: 5000,
                maximumAge: 0
     },
     getGeolocation : function(){
                // Set deferred action
                _def = $.Deferred(navigator.geolocation.getCurrentPosition(success, error, GoogleAPI.options));

                // allows chaining
                return this;
     },
     getCity : function(callback){
        _def.done(function(){
            var city = "";

            $.getJSON( _jsonURL, function( json ) {
               //check if access to the API was denied
               if (json.status == "REQUEST_DENIED"){
                        console.error("API access denied.")
                        callback(null);
                        return;
                    };

               var arr = $.map(json, function(el) { return el; })

               city = arr[3]["address_components"][0]["long_name"];
               console.log(city);

               callback(city);
            })
            .fail(function(){
               console.warn("failed to getCity");              
               callback(null);
            }); //end getJSON          
         }); //end _def

         // allows chaining
         return this;
     } //end getCity
 }; //end window.GoogleAPI 



  function success(pos) {
     _coords = pos.coords;
     _latitude = _coords.latitude;
     _longitude = _coords.longitude;
     _jsonURL = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + _latitude  + "," + _longitude + "&key=" + APIKEY; 

     console.log(_jsonURL);
     console.log(`Latitude : ${_coords.latitude}`);
     console.log(`Longitude: ${_coords.longitude}`);

     // Tell the promise the deferred action has been completed
     _def.resolve();
  };

  function error(err) {
     console.warn(`ERROR(${err.code}): ${err.message}`);

     // Tell the promise the deferred action has failed
     _def.reject();
  };

}(window))

GoogleAPI.getGeolocation()
         .getCity(function(data){
             if(data){
                // do something with the data
                 alert(data);
             }
         });

有关承诺的说明:

承诺/延期功能是一个沉重的主题。从技术上讲,$ .getJSON是一个假定成功的承诺(尽管它们包含.fail()用于错误处理。)

var _def = $.Deferred(navigator.geolocation.getCurrentPosition(success, error, GoogleAPI.options)); <-- create a deferred action (a promise.)

Promise是异步函数。通常在获取数据时出现延迟。

_def.resolve(); <-- Says the promised action took place. 
_def.reject(); <-- Says the promised action failed.
_def.done(function(){}) <-- runs if promised action was successful. 
_def.fail(function(){}) <-- runs id promised action failed.