如何返回getLocation函数的坐标,返回纬度和经度

时间:2018-01-15 06:59:20

标签: javascript function geolocation return latitude-longitude

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

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

其他信息:     
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;

1 个答案:

答案 0 :(得分:0)

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

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

  1. 使用地理位置API获取当前位置
  2. 使用AJAX请求获取天气数据
  3. 制作显示结果所需的任何DOM更新
  4. 使用回调模式的示例实现:

    &#13;
    &#13;
    // 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);
        });
      });
    }
    &#13;
    <button onclick="handleClick()">Get Weather Data</button>
    &#13;
    &#13;
    &#13;