Leaflet.js – Calling OpenWeatherMap API in Leaflet.js Map

leafletopenweathermap-api

How to get weather data from OpenWeatherMap API in a popup by clicking any location on the map?

i am still new at calling APIs in my map, API return JSON files but i don't know how to call the API in my map and how to bind JSON file in an HTML element.

This is the API which uses coordinates to return weather data in a JSON file: api.openweathermap.org/data/2.5/weather?lat=35&lon=139

but i need to replace these lat and lng parameters by clicking any location on the map.

Best Answer

You should be able to do something like this

var mymap = L.map('maptest').setView([51.505, -0.09], 13);

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '© OSM contributors'
}).addTo(mymap)

var popup = L.popup()

function onMapClick(e) {
    popup
        .setLatLng(e.latlng)
        .setContent("Fetching weather info")
        .openOn(mymap);

    fetch('https://api.openweathermap.org/data/2.5/weather?lat=' + e.latlng.lat + '&lon=' + e.latlng.lng + '&appid=' + yourApiKey)
        .then(r => r.json()) 
        .then(data => { 
            // Change this line to show exactly the info you need
            popup.setContent(data.weather.map(w => w.description).join(", "))
        })
}

mymap.on('click', onMapClick)

The example is using the fetch api to call the openweathermap api and fetch is only supported in modern browsers. If you need to support older browsers you need to use a polyfill (https://github.com/github/fetch)

Edit: As mentioned by @Spacedman in the comments, the above solution should only be used on private networks. If you use the above code on public available networks, you expose your apikey for openweathermap so that anyone can use it to request the service.