Openweathermap処理まとめ


なんとなく気に食わなかったのでとりあえず処理まとめ

Openweathermap

もう少しまとめたりLeafletぽくまとめるべきな気がするが…。

var MapWeather = function (map, cnt) {
  this.map = map;
  this.cnt = cnt;
  this.group = L.layerGroup().addTo(map);
  this._handle = null;
  this._findUrl = 'http://api.openweathermap.org/data/2.5/find?lat={lat}&lon={lng}&cnt={cnt}';
  this._iconUrl = 'http://openweathermap.org/img/w/{icon}.png';
  this.init();
}
MapWeather.prototype = {
  init: function () {
    this.map.on("move", this._onMapMove.bind(this));
  },
  _onMapMove: function () {
    console.log('Move');
    if (this._handle) {
      window.clearTimeout(this._handle);
      this._handle = null;
    }
    var cnt = this.cnt;
    var map = this.map;
    var getJson = this._getJson.bind(this);
    var urlBase = this._findUrl;

    this._handle = window.setTimeout(function () {
      var centerPt = map.getCenter();
      var url = L.Util.template(urlBase, {
        lat: centerPt.lat,
        lng: centerPt.lng,
        cnt: cnt
      });
      console.log(url);
      $.getJSON(url, getJson);
    });
  },
  _getJson: function (jsonObj) {
    var group = this.group;
    var iconUrlBase = this._iconUrl;

    console.log(jsonObj);
    if (!jsonObj || !jsonObj.list || !jsonObj.list.length || jsonObj.list.length < 1)
      return;
    group.clearLayers();

    for (var i = jsonObj.list.length; i--;) {
      var jobj = jsonObj.list[i];
      if (!jobj.coord || !jobj.weather || !jobj.weather.length || jobj.weather.length < 1)
        continue;

      var weather = jobj.weather[0];
      if (!weather.icon)
        continue;
      //var iconUrlBase = this._iconUrl;
      var iconUrl = L.Util.template(iconUrlBase, {
        icon: weather.icon
      });
      var icon = new L.Icon({ iconAnchor: [25, 25], iconUrl: iconUrl });

      var pt = jobj.coord
      var marker = L.marker([pt.lat, pt.lon], { icon: icon });
      if (jobj.name)
        marker.bindPopup(jobj.name);
      group.addLayer(marker);
    }
  }
};

var map = L.map('map').setView([35.7, 140], 10);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(map);

var aaa = new MapWeather(map, 3);
カテゴリー: 開発 タグ: パーマリンク