Search code examples
javascripthtmlasp.netgoogle-mapsapi-design

Googlemaps Api weird behavior


I decided to have a play around with googlemaps and the ISS api to build a basic tracker. I plan on adding a bunch of stuff to this but for now this is kept simple.

The problem i am having is, i can set dummy values in the asp:Labels for Latitude & Longitude then populate a string with them that i can use with google maps.

var ISS = { lat: parseFloat(document.getElementById('lblLat').innerText), lng: parseFloat(document.getElementById('lblLong').innerText) };

This works, when i then try use the values i get from the json callback even though i can see these when i use console.log(), they do not work.

ISS = { lat: data['iss_position']['latitude'], lng: data['iss_position']['longitude'] };

I have tried instead of reading directly adding back to the asp:Label's then reading however it does not work either.

What am i doing wrong? I have tried not to add any complexity to this while i toy with googlemaps api but this not working is confusing me as i dont see whats different with dummy values vs what i get from an api. webpage

Below is all my code for this page.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ISS.aspx.cs" Inherits="WebApps.IIS" %>

<!DOCTYPE html>
<html>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <head runat="server">
        <title>ISS Tracker</title>
        <style>
          #map {
            height: 400px;  /* The height is 400 pixels */
            width: 100%;  /* The width is the width of the web page */
           }
          #pageTitle{
              margin: auto;
              padding: 10px;
          }
        </style>
    </head>
    <body>
        <div id="pageTitle">
            <h3>ISS Tracker</h3>
            <h4>International Space Station</h4>
        </div>
        <form runat="server">
            <label>Latitude: </label><asp:Label runat="server" ID="lblLat"/><br />
            <label>Longitude: </label><asp:Label runat="server" ID="lblLong"/><br />
            <label>Time: </label><asp:Label runat="server" ID="lblTime" Text="13/02/2020 15:45:00" /><br />
            <asp:Button runat="server" ID="btnRefresh" Text="Refresh" onClick="btnRefresh_Click" style="height: 26px" />
            <div id="map"></div>
        </form>
        <script>

            //globals
            var map;
            var ISS;// = { lat: parseFloat(document.getElementById('lblLat').innerText), lng: parseFloat(document.getElementById('lblLong').innerText) };
            var image = 'http://icons.iconarchive.com/icons/goodstuff-no-nonsense/free-space/256/international-space-station-icon.png'

            // Initialize and add the map
            function initMap() {
                // The location of ISS
                $.getJSON('http://api.open-notify.org/iss-now.json?callback=?', function (data) {
                    ISS = { lat: data['iss_position']['latitude'], lng: data['iss_position']['longitude'] }; 
                    console.log("latitude: " + data['iss_position']['latitude'] + " & longitude: " + data['iss_position']['longitude']);
                    document.getElementById('lblLat').innerText = data['iss_position']['latitude'];
                    document.getElementById('lblLong').innerText = data['iss_position']['longitude'];
                });
                // The map, centered at ISS
                map = new google.maps.Map(
                    document.getElementById('map'), { zoom: 10, center: ISS });
                // The marker, positioned at ISS
                var marker = new google.maps.Marker({
                    position: ISS,
                    map: map,
                    icon: {
                        url: image,
                        scaledSize: new google.maps.Size(128, 128),
                        size: new google.maps.Size(128, 128)
                    }
                });
                marker.position = ISS;

            }

            //Will use later when i want to update
            function moveISS() {
                $.getJSON('http://api.open-notify.org/iss-now.json?callback=?', function (data) {
                    var lat = data['iss_position']['latitude'];
                    var lon = data['iss_position']['longitude'];
                    ISS = { lat: lat, lng: lon }; 
                    document.getElementById('lblLat').innerText = lat;
                    document.getElementById('lblLong').innerText = lon;
                });
                setTimeout(moveISS, 5000);
            } 
        </script>
        <script async defer src="https://maps.googleapis.com/maps/api/js?key=*****api key *****&callback=initMap">
        </script>
    </body>
</html>

Solution

  • Your problem is due to when things happen

    Your getJSON call launches and then will return with a data response at some point in the future, however the rest of your code (with an invalid value for ISS) will execute immediately

    var map;
    var image = 'http://icons.iconarchive.com/icons/goodstuff-no-nonsense/free-space/256/international-space-station-icon.png';
    
    // ISS start position
    var ISS  = { lat: 0.0, lng: 0.0 };
    
    function initMap() {
      // create the map and marker before you know where ISS is
      // The map, centered at ISS
       map = new google.maps.Map(
         document.getElementById('map'), { zoom: 10, center: ISS });
       // The marker, positioned at ISS
       var marker = new google.maps.Marker({
         position: ISS,
         map: map,
         icon: {
           url: image,
           scaledSize: new google.maps.Size(128, 128),
           size: new google.maps.Size(128, 128)
         }
       });
    
    
    }
    
    function updateISS() {
      // The location of ISS
      $.getJSON('http://api.open-notify.org/iss-now.json?callback=?', 
         function (data) {
           ISS = { 
             lat: data['iss_position']['latitude'], 
             lng: data['iss_position']['longitude'] 
           };
    
           // update the Marker position here
           marker.setPosition(ISS);
    
           console.log("latitude: " + ISS['lat'] + " & longitude: " + ISS['lng']);
           document.getElementById('lblLat').innerText = ISS['lat'];
           document.getElementById('lblLong').innerText = ISS['lng'];
         });
    
    }
    
    // update ISS position every 5 seconds.
    var repeat = setInterval( updateISS, 5000)
    

    The above is a first pass at a solution, creating the map and the marker before the getJSON call and updating the marker position when the JSON response is obtained.

    Also I would note you're using a mixture of JavaScript and JQuery which ain't pretty