0

I'm building an ip address tracker which has a text input and a map below. The whole app almost works as intended, the only issue is that when I enter a new ip address in the input after the window load, I can no longer drag the map, it becomes fixed in place.

let IP_ADDRESS = document.querySelector('.ip-address');
let loc = document.querySelector('.ip-location');
let timezone = document.querySelector('.ip-timezone');
let isp = document.querySelector('.ip-isp');
let array = [];
 

function SearchIp(e, ipAddress){
    e.preventDefault()

    const userInputIp = document.querySelector('#user-input').value;
      // key and ip address variables
      const key = 'at_i2aWTD38COX3urd2INjt8nvY6Sm3I';

      fetch(`https://geo.ipify.org/api/v1?apiKey=${key}&ipAddress=${userInputIp ? userInputIp : ''}`)
      .then((res) => res.json())
      .then((data) => {
          
          // Append api data to body
         IP_ADDRESS.innerText = data.ip;
         loc.innerText = `${data.location.city !== "" ? data.location.city + ', ' : "N/A"}${data.location.city !== "" ? data.location.country : ''}`;
         timezone.innerText = `${data.location.timezone !== "" ? `UTC ${data.location.timezone}` : "N/A"}` 
         isp.innerText = data.isp !== "" ? data.isp : "N/A";

        //   Stops error (map not initialised)
         let container = L.DomUtil.get('map'); if(container != null){ container._leaflet_id = null; }
          // Map Initialization
            let map = L.map('map').setView([data.location.lat, data.location.lng], 13);
            let marker = L.marker([data.location.lat, data.location.lng]).addTo(map);

            L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
               maxZoom: 19,
               attribution: '© OpenStreetMap'
           }).addTo(map);
      })
}

document.querySelector('#search').addEventListener('submit', (e) => SearchIp(e));
window.addEventListener('load', SearchIp)
Ope Afolabi
  • 127
  • 12

1 Answers1

0

I found this answer here on stackoverflow: refresh leaflet map: map container is already initialized

which helps me solve this problem, I needed to add

if(map){
      map.remove();
      map = undefined
  }
Ope Afolabi
  • 127
  • 12