【问题标题】:how to automate a geolocation based Json如何自动化基于地理位置的 Json
【发布时间】:2019-11-19 16:15:55
【问题描述】:

我是初学者,我有一个功能可以根据您的位置获取链接。

函数如下:

 
    <p id="demo"></p>

    <script>
    var x = document.getElementById("demo");

    function getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition, showError);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
      }
      }
     
      function showPosition(position) {
       x.innerHTML =  "http://api.openweathermap.org/data/2.5/weather?lat=" + position.coords.latitude + "&lon=" +
        position.coords.longitude + "&units=metric&APPID=3d1523ca3f27251ddf055b1b26ed347f"
      }
       

    </script>

现在我正在尝试将此链接放入 get.Json 中,以便网站自动获取有关您所在地区的天气信息。问题是我无法让它工作。有人可以帮助我如何将链接自动获取到 get.Json 中。

【问题讨论】:

  • 把你用来调用链接的代码。
  • 你的意思是:
  • x.innerHTML = "http://api.openweathermap... 这只是将您的元素设置为某个 url 字符串。要获取数据,您需要发出一些 ajax 请求,XMLHTTPRequestfetch()、jQuery.ajax() 等
  • 这是我第一次编码,我还不知道 ajax 是如何工作的,你能举个例子吗?
  • 这是我们的 Json: $.getJSON ("We want the link here", function(data){ console.log(data); var name = data.name; var temp = Math.round (data.main.temp); $('.temp').append("het is nu"+ temp + "℃ in").append(name) });

标签: javascript html json geolocation openweathermap


【解决方案1】:

要从某个 web api 端点获取数据,您需要使用一些 ajax 请求 api。原生的是XMLHTTPRequestfetch()

还有jQuery.ajax及其别名$.post,$.get,$.getJSON

所以只需使用您熟悉的 api 并将其添加到您的 showPosition 函数中。当相应 api 的 promise 或事件回调被触发时,使用传递的数据显示您的信息:

function showPosition(position) {
  let apiUrl = "http://api.openweathermap.org/data/2.5/weather?lat=" + 
               position.coords.latitude + 
               "&lon=" + position.coords.longitude + 
               "&units=metric&APPID=3d1523ca3f27251ddf055b1b26ed347f";

  //using fetch() api
  fetch(apiUrl).then(response=>response.json()).then(data=>{
    //use the returned data however you like
    //for instance show temperature
    x.innerHTML = data.main.temp;
  });

  //using XMLHttpRequest
  let req = new XMLHttpRequest();
  req.open("get",apiUrl);
  req.addEventListener('load',function(data){
    //use the returned data however you like
  });

  //using a library like jQuery
  jQuery.getJSON(apiUrl).then(function(data){
    //use the returned data however you like
  });
}

阅读异步操作并避免以下陷阱:

How do I return the response from an asynchronous call?

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多