Geolocation - PLZ

by scurrilus

HTML

<link rel="stylesheet" href="http://alertifyjs.com/build/css/alertify.css">
<link rel="stylesheet" href="http://alertifyjs.com/build/css/themes/default.css">
<script src="http://alertifyjs.com/build/alertify.js"></script>

JavaScript

const postalCodes = ['12621', '12555']
const geocodeApiKey = '###'

if ("geolocation" in navigator) {
  // Get the current position
  navigator.geolocation.getCurrentPosition(async function(position) {
    // Get the latitude and longitude from the position object
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
    
    // Do something with the latitude and longitude
    console.log("Latitude: " + latitude + ", Longitude: " + longitude);
    
    // Define and call the fetchData function
    async function fetchData() {
      try {
          const response = await fetch('https://geocode.maps.co/reverse?lat=' + latitude + '&lon=' + longitude + `&api_key=${geocodeApiKey}`);

          if (!response.ok) {
              throw new Error('Network response was not ok.');
          }

          const data = await response.json();
          console.log(data);

          if (postalCodes.includes(data.address.postcode)) {
    				console.log(`postCode '${data.address.postcode}' is part of the test array.`);
          } else {
            console.log(`postCode '${data.address.postcode}' is not part of the test array.`);
          }
      } catch (error) {
          console.error('Error fetching data:', error);
      }
    } 

    // Call the fetchData function
    fetchData();
  });
}