我用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
答案 0 :(得分:0)
如果您事先知道要支持的城市列表,则可以使用名为Here的city.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);
});