如何return一个getLocation函数的坐标,return经纬度

How to return the coordinates of a getLocation function, return latitude and longitude

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

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

补充信息:
代码笔: https://codepen.io/rogercodes/pen/gXvOoO
freeCodeCampAPI: 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;

地理定位 API 是一个异步操作。最好使用 Promises (if available ) or the 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);
    });
  });
}
<button onclick="handleClick()">Get Weather Data</button>