Windows alert method inside function triggers twice

Viewed 69

I'm learning JavaScript, while doing so I'm exploring the Google Maps API. My .htm script below runs as intended (for now) except for a bothersome Window alert method that seems to trigger twice upon execution of that part of the script. I have no idea why - any explanation or clarification on this would be much welcome. I have a feeling it may have something to do with the structure of my script.

<!DOCTYPE html>
     <html>
     <head>
       <title>GPS coordinates to map TEST</title>
     <style>
     #map {
       width: 500px;
       height: 380px;
     }
        
     body {
       font-family: arial;
       font-size: 13px;
     }
        
     </style>
     </head>
     <body onload="init()">
     <p>Click below to get your coordinates and display your current position on a map:</p>
     <input type="button" id="btn" onclick="get_location()" value="Where am I?">
     <p>Or provide coordinates to display the position entered on a map:</p>
     Latitude: <input type="number" id="in_lat"> Longitude: <input type="number" id="in_lon">
     <p><input type="button" id="btn_2" onclick="find_location()" value="Show"></p>
     <p id="output"></p>
     <div id="map"></div>
     <script src="http://maps.googleapis.com/maps/api/js"></script>
     <script>
     var x = document.getElementById("output");
     var y = document.querySelector("#btn").value;
        
     function init() {
      var z = document.getElementById("btn") 
      google.maps.event.addDomListener(z, "click", get_location);
     }
        
     function get_location() {
      if (y == "Where am I?") {
      document.querySelector("#btn").value = "Update";
      }
        
      if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(show_position, show_error);
      } 
      else { 
      x.innerHTML = "Geolocation is not supported by your browser.";
      }
     }
        
     function show_position(position) {
      var latitude = position.coords.latitude;
      var longitude = position.coords.longitude;
      var altitude = (position.coords.altitude == null) ? "Data not available" : altitude;
        
      x.innerHTML = "Latitude: " + latitude + 
      "<br>Longitude: " + longitude +
      "<br>Accuracy: " + position.coords.accuracy +
      "<br>Altitude: " + altitude;
        
      alert("Latitude: " + latitude + "\nLongitude: " + longitude); //<------------offending method
      display_map(latitude, longitude);
     }
        
     function display_map(lat, lon) {
      var point = new google.maps.LatLng(lat,lon);
      var map_prop = {
      center:point,
      zoom:5,
      mapTypeId:google.maps.MapTypeId.ROADMAP
      };
        
      var map = new google.maps.Map(document.getElementById("map"),map_prop);
        
      var marker = new google.maps.Marker({
      position:point,
      });
      marker.setMap(map);
     }
        
     function show_error(error) {
      switch(error.code) {
      case error.PERMISSION_DENIED:
      x.innerHTML = "User denied the request for Geolocation."
      break;
      case error.POSITION_UNAVAILABLE:
      x.innerHTML = "Location information is unavailable."
      break;
      case error.TIMEOUT:
      x.innerHTML = "The request to get user location timed out."
      break;
      case error.UNKNOWN_ERROR:
      x.innerHTML = "An unknown error occurred."
      break;
      }
      document.getElementById("map").innerHTML = "Oops something went wrong";
     }
        
     function find_location() {
      var latitude_in = document.getElementById("in_lat").value;
      var longitude_in = document.getElementById("in_lon").value; 
        
      if (latitude_in.length <= 0 || longitude_in.length <= 0) {
      alert("Please enter values correctly");
      }
      else {
      var latitude = Number(latitude_in).toFixed(7);
      var longitude = Number(longitude_in).toFixed(7);
      alert("Latitude: " + latitude + "\nLongitude: " + longitude);
      x.innerHTML = "Latitude: " + latitude + 
      "<br>Longitude: " + longitude;
      display_map(latitude, longitude);
      }
     }
     </script>
     </body>
     </html>
1 Answers

It is a typo in your code. You are adding the "click" event listener to the button twice.

Once in the HTML:

<input type="button" id="btn" onclick="get_location()" value="Where am I?">

Once in the JavaScript:

google.maps.event.addDomListener(z, "click", get_location);

That makes the get_location function fire twice for each click on the button. Remove one of them and it will work as you expect.

code snippet:

<!DOCTYPE html>
<html>

<head>
  <title>GPS coordinates to map TEST</title>
  <style>
    #map {
      width: 500px;
      height: 380px;
    }
    
    body {
      font-family: arial;
      font-size: 13px;
    }
  </style>
</head>

<body>
  <p>Click below to get your coordinates and display your current position on a map:</p>
  <input type="button" id="btn" onclick="get_location()" value="Where am I?">
  <p>Or provide coordinates to display the position entered on a map:</p>
  Latitude: <input type="number" id="in_lat"> Longitude: <input type="number" id="in_lon">
  <p><input type="button" id="btn_2" onclick="find_location()" value="Show"></p>
  <p id="output"></p>
  <div id="map"></div>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
  <script>
    var x = document.getElementById("output");
    var y = document.querySelector("#btn").value;

    function get_location() {
      if (y == "Where am I?") {
        document.querySelector("#btn").value = "Update";
      }

      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(show_position, show_error);
      } else {
        x.innerHTML = "Geolocation is not supported by your browser.";
      }
    }

    function show_position(position) {
      var latitude = position.coords.latitude;
      var longitude = position.coords.longitude;
      var altitude = (position.coords.altitude == null) ? "Data not available" : altitude;

      x.innerHTML = "Latitude: " + latitude +
        "<br>Longitude: " + longitude +
        "<br>Accuracy: " + position.coords.accuracy +
        "<br>Altitude: " + altitude;
      alert("Latitude: " + latitude + "\nLongitude: " + longitude); //<------------offending method
      display_map(latitude, longitude);
    }

    function display_map(lat, lon) {
      var point = new google.maps.LatLng(lat, lon);
      var map_prop = {
        center: point,
        zoom: 5,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };

      var map = new google.maps.Map(document.getElementById("map"), map_prop);

      var marker = new google.maps.Marker({
        position: point,
      });
      marker.setMap(map);
    }

    function show_error(error) {
      switch (error.code) {
        case error.PERMISSION_DENIED:
          x.innerHTML = "User denied the request for Geolocation."
          break;
        case error.POSITION_UNAVAILABLE:
          x.innerHTML = "Location information is unavailable."
          break;
        case error.TIMEOUT:
          x.innerHTML = "The request to get user location timed out."
          break;
        case error.UNKNOWN_ERROR:
          x.innerHTML = "An unknown error occurred."
          break;
      }
      document.getElementById("map").innerHTML = "Oops something went wrong";
    }

    function find_location() {
      var latitude_in = document.getElementById("in_lat").value;
      var longitude_in = document.getElementById("in_lon").value;

      if (latitude_in.length <= 0 || longitude_in.length <= 0) {
        alert("Please enter values correctly");
      } else {
        var latitude = Number(latitude_in).toFixed(7);
        var longitude = Number(longitude_in).toFixed(7);
        alert("Latitude: " + latitude + "\nLongitude: " + longitude);
        x.innerHTML = "Latitude: " + latitude +
          "<br>Longitude: " + longitude;
        display_map(latitude, longitude);
      }
    }
  </script>
</body>

</html>

Related