【问题标题】:How to return the coordinates of a getLocation function, return latitude and longitude如何返回一个getLocation函数的坐标,返回经纬度
【发布时间】:2018-01-15 06:59:19
【问题描述】:

我正在尝试使用 freeCodeCamp API 为天气项目构建天气 API。

我想要做的是使用 getLocation 函数来获取纬度和经度,然后将它们作为变量返回,然后我可以使用它来连接到 URL。 通过使用 URL,我可以获得输出华氏度所需的 json 信息以及我需要的任何其他信息。 由于我需要 https 连接,因此我使用 codepen 进行测试。

附加信息:
代码笔: https://codepen.io/rogercodes/pen/gXvOoO
freeCodeCamp API: https://fcc-weather-api.glitch.me/

HTML

<html>
<head>

  <!-- <link rel="stylesheet" type="text/css" 
href="css/quoteStyles.css"> -->
</head>
<body>

<button onclick="getWeather(finalLat,finalLon)">getWeather</button>
<p>What is</p>

<button onclick="getLocation()">Try It</button>


<p id='geoAPI'>Geo API</p>
<p id="lan">Test Lan: </p>
 <p id='geo'>geoLocal</p><script>

 </script>
</body>
<script src="javascript/weatherTest.js"></script>
<!-- <script src="JSON/weather.json"></script> -->

Javascript

var api= "https://fcc-weather-api.glitch.me/api/current?";
var googleApi="https://www.googleapis.com/geolocation/v1/geolocate?
key=AIzaSyCOMzDSyP4RkXwp7mSiFiuAZroyrazU5eM";

var lat, lon;
var x= document.getElementById("geoLocal");
var tempX= document.getElementById("temp");
var geoLocal=document.getElementById("geo");
var xLat= document.getElementById("lat");
// Following functions will get the latitude and longitude

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        geoLocal.innerHTML = "Geolocation is not supported by this 
 browser.";
    }
}
var finalLat=finalCoords[0];
var finalLon=finalCoords[1];
function showPosition(position){
  geoLocal.innerHTML="Latitude:" + position.coords.latitude +
  "<br> Longitude: " + position.coords.longitude;
  lat= position.coords.latitude;
  lon=position.coords.longitude;
  var finalCoords=[lat,lon]
  return finalCoords;
}
showPosition(position);
console.log(api,lon);
xLat.innerHTML="testLat: " + finalCoords[0];
finalLat=finalCoords[0];
finalLon=finalCoords[1];

function getWeather(finalLat,finalLon){
  var completeApi=api+lon+"&"+lat;
  // lon="lon="+ position.coords.longitude;
  // lat='lat='+ position.coords.latitude;
  xLat.innerHTML="testLatitude: " +completeApi;

  return completeApi;
  }
getWeather(finalLat,finalLon);

下面的注释信息是我将用来完成输出任何用户位置的天气的额外工作。

// var completeApi="getWeather(lat,lon)";
// JSON request for API to get temperature
// var ourRequest= new XMLHttpRequest();
// ourRequest.open('GET',completeApi);
// ourRequest.onload= function() {
//   if (ourRequest.status>= 200 && ourRequest.status<400){
//     var ourData= JSON.parse(ourRequest.responseText);
//     renderHTML(ourData);
//     console.log("ourData",ourData);
// } else{
//   console.log("Connection Error, Please try again.")
// }
// };

// ourRequest.send();
// console.log(ourRequest)

// var jsonWeather= JSON.stringify(ourData);
// document.body.innerHTML=jsonWeather;
// function renderHTML(data){
//   var htmlString="";
//   for (i=0;i<data.lenth;i++){
//     htmlString=data[i].coord;
//     console.log(data[i].coord)
//     tempX.textContent= data;

//   }
//   // htmlString.textContent=data[0];
//   tempX.textContent= data;
//   // return data;
// }
// console.log(ourRequest)
// var geoLocation= document.getElementById("geoAPI");
// geoLocation.innerHTML=completeApi;

【问题讨论】:

    标签: javascript function geolocation return latitude-longitude


    【解决方案1】:

    地理位置 API 是一个异步操作。最好使用Promises(如果可用)或callback pattern 来实现这个用例。

    基本上需要按顺序进行以下异步操作:

    1. 使用地理定位 API 获取当前位置
    2. 使用 AJAX 请求获取天气数据
    3. 进行必要的 DOM 更新以显示结果

    使用回调模式的示例实现:

    // Helper to get the location from the browser
    function getLocation(cb) {
      cb = (cb && typeof cb === 'function' && cb) || function() {};
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(pos) {
          cb(null, [pos.coords.latitude, pos.coords.longitude]);
        });
      } else {
        cb(new Error('Browser does not support geolocation'));
      }
    }
    
    
    // Helper to make the AJAX call to the API
    function getWeather(coords, cb) {
      cb = (cb && typeof cb === 'function' && cb) || function() {};
      // Build URL
      var url = 'https://fcc-weather-api.glitch.me/api/current?lat=' + coords[0] + '&lon=' + coords[1];
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        // TODO: Handle error cases
        if (this.readyState == 4 && this.status == 200) {
          // TODO: Handle possible parse exception
          cb(null, JSON.parse(xhttp.responseText));
        }
      };
      xhttp.open("GET", url, true);
      xhttp.send();
    }
    
    // This gets triggered on clicking the button
    function handleClick() {
      //1. Get the current location using geolocation API
      getLocation(function(err, coords) {
        if (err) {
          // Handle error, return early
          return;
        }
    
        // 2. Get the weather data using an AJAX request
        getWeather(coords, function(err, data) {
          if (err) {
            // Handle error, return early
            return;
          }
          // Data is available here. Update DOM/process as needed
          // 3. Make whatever DOM updates necessary to show the results
          console.log(data);
        });
      });
    }
    &lt;button onclick="handleClick()"&gt;Get Weather Data&lt;/button&gt;

    【讨论】:

    • 您的答案有效。您能否解释以下部分的目的是什么?我主要是寻求帮助来解释添加/传递参数 cb。函数 getLocation(cb) { cb = (cb && typeof cb === 'function' && cb) ||功能() {}; if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(pos) { cb(null, [pos.coords.latitude, pos.coords.longitude]); }); } else { cb(new Error('浏览器不支持地理位置')); } }
    • 看来代码 sn-p 没有正确更改。我想请求解释 // Helper 从浏览器获取位置之后的第一个函数
    • 如果你指的是cb = (cb &amp;&amp; typeof cb === 'function' &amp;&amp; cb) || function() {}; 它检查参数是否被传递并且它是一个函数。如果不是,它使用一个空的无操作函数,因此脚本不会失败。该函数作为一个整体检查浏览器是否支持地理定位,如果可用则调用它。如果它不可用,则以错误作为第一个参数调用回调。您可以在handleClick 中传递给它的回调中对其进行测试,并在用户使用不支持地理位置的浏览器时向用户显示一条消息
    • 从技术上讲,您可以将getLocationgetWeather 组合为一个函数。为了可重用性,我将其分开,以防在代码中的其他地方使用位置
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 2011-08-24
    • 1970-01-01
    相关资源
    最近更新 更多