无法将我的纬度或经度附加到html文档?

时间:2016-06-08 02:17:51

标签: javascript jquery html css

我正在使用openweather api来显示用户所在城市的天气。我首先使用地理定位功能来查找用户的纬度和经度。然后该数据在变量api中传递。由于某种原因,纬度和经度不会附加到div id数据,api似乎也不起作用。

以下是codepen的链接:http://codepen.io/sibraza/pen/VjYwWK?editors=1111

这是JavaScript:

$(document).ready(function(){  
 var lat;
 var long; 

  if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {

    lat = position.coords.latitude; 
    long = position.coords.longitude; 


  var api='http://api.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+long+'&appid=(The API Key Was Removed in the question)';

  $.getJSON(api,function(data){
 var city= data.name; 

  console.log(api);
  console.log(city);
  });

  });

}

});

1 个答案:

答案 0 :(得分:0)

`function geoFindMe() {
  var output = document.getElementById("out");

  if (!navigator.geolocation){
    output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
    return;
  }

  function success(position) {
    var latitude  = position.coords.latitude;
    var longitude = position.coords.longitude;

    output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';

    var img = new Image();
    img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";

    output.appendChild(img);
  };

  function error() {
    output.innerHTML = "Unable to retrieve your location";
  };

  output.innerHTML = "<p>Locating…</p>";

  navigator.geolocation.getCurrentPosition(success, error);
}`

和HTml

`<p><button onclick="geoFindMe()">Show my location</button></p>
<div id="out"></div>

`

https://jsfiddle.net/api/mdn/