将json转换为javascript以获得实时天气

时间:2017-12-11 13:58:05

标签: javascript json google-api real-time weather

我正在尝试解析伦敦的实时天气数据并将其用作javascript对象。我正在使用谷歌api天气。这是我的代码。

<script>
  var map;
  var geoJSON;
  var request;
  var gettingData = false;
  // var openWeatherMapKey = "...........";
  function initialize() {
    var mapOptions = {
      zoom: 4,
      center: new google.maps.LatLng(50,-50)
    };
    map = new google.maps.Map(document.getElementById('map-canvas'),
        mapOptions);
    // Add interaction listeners to make weather requests
    google.maps.event.addListener(map, 'idle', checkIfDataRequested);
    // Sets up and populates the info window with details
    map.data.addListener('click', function(event) {
      infowindow.setContent(
       "<img src=" + event.feature.getProperty("icon") + ">"
       + "<br /><strong>" + event.feature.getProperty("city") + "</strong>"
       + "<br />" + event.feature.getProperty("temperature") + "&deg;C"
       + "<br />" + event.feature.getProperty("weather")
       );
      infowindow.setOptions({
          position:{
            lat: event.latLng.lat(),
            lng: event.latLng.lng()
          },
          pixelOffset: {
            width: 0,
            height: -15
          }
        });
      infowindow.open(map);
    });
  }
  var checkIfDataRequested = function() {
    // Stop extra requests being sent
    while (gettingData === true) {
      request.abort();
      gettingData = false;
    }
    getCoords();
  };
  // Get the coordinates from the Map bounds
  var getCoords = function() {
    var bounds = map.getBounds();
    var NE = bounds.getNorthEast();
    var SW = bounds.getSouthWest();
    getWeather(NE.lat(), NE.lng(), SW.lat(), SW.lng());
  };
  // Make the weather request
  var getWeather = function(northLat, eastLng, southLat, westLng) {
    gettingData = true;
    var requestString = "http://api.openweathermap.org/data/2.5/box/city?bbox="
                        + westLng + "," + northLat + "," //left top
                        + eastLng + "," + southLat + "," //right bottom
                        + map.getZoom()
                        + "&cluster=yes&format=json"
                        + "&APPID=" + "..........";
                        //this is the open weather map key
    request = new XMLHttpRequest();
    request.onload = proccessResults;
    request.open("get", requestString, true);
    request.send();
  };
  // Take the JSON results and proccess them
  var proccessResults = function() {
    console.log(this);
    var results = JSON.parse(this.responseText);
    if (results.list.length > 0) {
        resetData();
        for (var i = 0; i < results.list.length; i++) {
          geoJSON.features.push(jsonToGeoJson(results.list[i]));
        }
        drawIcons(geoJSON);
    }
  };
  var infowindow = new google.maps.InfoWindow();
  // For each result that comes back, convert the data to geoJSON
  var jsonToGeoJson = function (weatherItem) {
    var feature = {
      type: "Feature",
      properties: {
        city: weatherItem.name,
        weather: weatherItem.weather[0].main,
        temperature: weatherItem.main.temp,
        min: weatherItem.main.temp_min,
        max: weatherItem.main.temp_max,
        humidity: weatherItem.main.humidity,
        pressure: weatherItem.main.pressure,
        windSpeed: weatherItem.wind.speed,
        windDegrees: weatherItem.wind.deg,
        windGust: weatherItem.wind.gust,
        icon: "http://openweathermap.org/img/w/"
              + weatherItem.weather[0].icon  + ".png",
        coordinates: [weatherItem.coord.Lon, weatherItem.coord.Lat]
      },
      geometry: {
        type: "Point",
        coordinates: [weatherItem.coord.Lon, weatherItem.coord.Lat]
      }
    };
    console.log(feature);
    // Set the custom marker icon
    map.data.setStyle(function(feature) {
      return {
        icon: {
          url: feature.getProperty('icon'),
          anchor: new google.maps.Point(25, 25)
        }
      };
    });
    // returns object
    return feature;
  };
  // Add the markers to the map
  var drawIcons = function (weather) {
     map.data.addGeoJson(geoJSON);
     // Set the flag to finished
     gettingData = false;
  };
  // Clear data layer and geoJSON
  var resetData = function () {
    geoJSON = {
      type: "FeatureCollection",
      features: []
    };
    map.data.forEach(function(feature) {
      map.data.remove(feature);
    });
  };
  google.maps.event.addDomListener(window, 'load', initialize);

</script>

我希望只获得伦敦数据,优先考虑风数据,但可以使用所有数据。然后我想把这个数据/对象操作成交互式的东西。我有一个处理,直到这一点,我知道如何以及我想用js对象做什么,我只是无法克服这座桥。

任何想法?

这是json:

{"cod":200,"calctime":0.149010741,"cnt":13,"list":[{"id":4644585,"dt":1512993964,"name":"Nashville","coord":{"Lat":36.16589,"Lon":-86.784439},"main":{"temp":-2.42,"temp_min":-4,"temp_max":1,"pressure":1020,"humidity":92},"wind":{"speed":1.11,"deg":174.501},"rain":null,"snow":null,"clouds":{"today":1},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}]},{"id":4887398,"dt":1512993966,"name":"Chicago","coord":{"Lat":41.850029,"Lon":-87.650047},"main":{"temp":-3.45,"temp_min":-4,"temp_max":-3,"pressure":1017,"humidity":86},"wind":{"speed":2.1,"deg":180},"rain":null,"snow":null,"clouds":{"today":90},"weather":[{"id":600,"main":"Snow","description":"light snow","icon":"13n"},{"id":701,"main":"Mist","description":"mist","icon":"50n"}]},{"id":5128581,"dt":1512993707,"name":"New York","coord":{"Lat":40.714272,"Lon":-74.005966},"main":{"temp":0.24,"temp_min":-1,"temp_max":2,"pressure":1017,"humidity":69},"wind":{"speed":3.41,"deg":253.501},"rain":null,"snow":null,"clouds":{"today":90},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04n"}]},{"id":5128638,"dt":1512993699,"name":"New York","coord":{"Lat":43.000351,"Lon":-75.499901},"main":{"temp":-3,"temp_min":-3,"temp_max":-3,"pressure":1014,"humidity":100},"wind":{"speed":3.1,"deg":290},"rain":null,"snow":null,"clouds":{"today":90},"weather":[{"id":600,"main":"Snow","description":"light snow","icon":"13n"},{"id":701,"main":"Mist","description":"mist","icon":"50n"}]},{"id":6324729,"dt":1512993743,"name":"Halifax","coord":{"Lat":44.645329,"Lon":-63.572392},"main":{"temp":-0.07,"temp_min":-1,"temp_max":1,"pressure":1015,"humidity":86},"wind":{"speed":1,"deg":10},"rain":null,"snow":null,"clouds":{"today":90},"weather":[{"id":620,"main":"Snow","description":"light shower snow","icon":"13n"}]},{"id":6324733,"dt":1512993743,"name":"St. Johns","coord":{"Lat":47.564941,"Lon":-52.709309},"main":{"temp":2.49,"temp_min":2,"temp_max":3,"pressure":1013,"humidity":86},"wind":{"speed":3.1,"deg":190},"rain":null,"snow":null,"clouds":{"today":90},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}]},{"id":3372783,"dt":1512993760,"name":"Ponta Delgada","coord":{"Lat":37.73333,"Lon":-25.66667},"main":{"temp":16,"temp_min":16,"temp_max":16,"pressure":1027,"humidity":72},"wind":{"speed":7.2,"deg":360},"rain":null,"snow":null,"clouds":{"today":75},"weather":[{"id":521,"main":"Rain","description":"shower rain","icon":"09d"}]},{"id":3117735,"dt":1512993779,"name":"Madrid","coord":{"Lat":40.4165,"Lon":-3.70256},"main":{"temp":8.57,"temp_min":7,"temp_max":10,"pressure":996,"humidity":81},"wind":{"speed":6.2,"deg":240},"rain":null,"snow":null,"clouds":{"today":75},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}]},{"id":2964574,"dt":1512993860,"name":"Dublin","coord":{"Lat":53.34399,"Lon":-6.26719},"main":{"temp":0.49,"temp_min":0,"temp_max":1,"pressure":992,"humidity":100},"wind":{"speed":5.7,"deg":290},"rain":null,"snow":null,"clouds":{"today":20},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}]},{"id":2643741,"dt":1512993916,"name":"City of London","coord":{"Lat":51.512791,"Lon":-0.09184},"main":{"temp":1.61,"temp_min":1,"temp_max":2,"pressure":982,"humidity":93},"wind":{"speed":5.7,"deg":10},"rain":null,"snow":null,"clouds":{"today":90},"weather":[{"id":611,"main":"Snow","description":"sleet","icon":"13d"},{"id":701,"main":"Mist","description":"mist","icon":"50d"},{"id":500,"main":"Rain","description":"light rain","icon":"10d"}]},{"id":2507480,"dt":1512993702,"name":"Algiers","coord":{"Lat":36.752499,"Lon":3.04197},"main":{"temp":20,"temp_min":20,"temp_max":20,"pressure":1002,"humidity":37},"wind":{"speed":9.8,"deg":180},"rain":null,"snow":null,"clouds":{"today":75},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}]},{"id":3128760,"dt":1512993780,"name":"Barcelona","coord":{"Lat":41.38879,"Lon":2.15899},"main":{"temp":13,"temp_min":13,"temp_max":13,"pressure":990,"humidity":71},"wind":{"speed":5.1,"deg":240},"rain":null,"snow":null,"clouds":{"today":20},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}]},{"id":2988507,"dt":1512993913,"name":"Paris","coord":{"Lat":48.853409,"Lon":2.3488},"main":{"temp":7.86,"temp_min":7,"temp_max":9,"pressure":969,"humidity":81},"wind":{"speed":10.8,"deg":200},"rain":null,"snow":null,"clouds":{"today":90},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}]}]}

0 个答案:

没有答案