如何自动基于地理位置的Json

问题描述 投票:1回答:1

我是初学者,并且具有根据您的位置获取链接的功能。

这里是功能:

 
    <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。

javascript html json geolocation openweathermap
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.