I have developed an event registration website in PHP. When users view the event, I have to show the weather condition of that location. I've got the code from
https://openweathermap.org/widgets-constructor
And Code is here:
<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>
But I want know how to pass city id dynamically
If you know the list of cities you want to support beforehand, you can use the list called city.list.json.gz
listed Here to create a map of selected cities which you can use to dynamically look up the cityId
and replace that parameter in the snippet you have shared
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);
});
<button class="selector" data-city="bangalore">Bangalore</button>
<button class="selector" data-city="mumbai">Mumbai</button>
<div id="openweathermap-widget-14"></div>
</div>