在php中显示事件位置的天气状况

时间:2018-06-27 06:42:07

标签: javascript php openweathermap

我用PHP开发了一个事件注册网站。当用户查看事件时,我必须显示该位置的天气情况。我已经从

获得了代码

https://openweathermap.org/widgets-constructor

代码在这里:

<div id="openweathermap-widget-14"></div>

<script>
window.myWidgetParam ? window.myWidgetParam : window.myWidgetParam = [];
window.myWidgetParam.push({
    id: 14,
    cityid: '1254589',
    appid: '<appId>', // Anonymised appId
    units: 'metric',
    containerid: 'openweathermap-widget-14',
});
(function () {
    var script = document.createElement('script');
    script.async = true;
    script.charset = "utf-8";
    script.src = "//openweathermap.org/themes/openweathermap/assets/vendor/owm/js/weather-widget-generator.js";
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(script, s);
})();
</script>

但是我想知道如何动态传递城市ID

1 个答案:

答案 0 :(得分:0)

如果您事先知道要支持的城市列表,则可以使用名为Herecity.list.json.gz列表来创建所选城市的地图,您可以用来动态查找{ {1}},然后在您共享的代码段中替换该参数

cityId
var cityMap = {
  "mumbai": {
    id: 1275339,
    displayName: 'Mumbai'
  },
  "bangalore": {
    id: 1277333,
    displayName: 'Bangalore'
  }
}

function loadWeather(containerId, city) {
  var cityId = cityMap[city].id;
  window.myWidgetParam = [];
  window.myWidgetParam.push({
    id: 14,
    cityid: cityId,
    appid: '<appId>', // Anonymised app Id
    units: 'metric',
    containerid: containerId,
  });
  (function() {
    var script = document.createElement('script');
    script.async = true;
    script.charset = "utf-8";
    script.src = "//openweathermap.org/themes/openweathermap/assets/vendor/owm/js/weather-widget-generator.js";
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(script, s);
  })();
}


function handleButtonClick(e) {
  var city = e.target.dataset.city || 'bangalore';
  loadWeather("openweathermap-widget-14", city);
}

Array.from(document.getElementsByClassName('selector')).forEach(function(el){
  el.addEventListener('click', handleButtonClick);
});