【问题标题】:Googlemaps Api weird behaviorGoogle Maps Api 奇怪的行为
【发布时间】:2020-06-03 16:21:38
【问题描述】:

我决定尝试使用 googlemaps 和 ISS api 来构建一个基本的跟踪器。我计划为此添加一堆东西,但现在这很简单。

我遇到的问题是,我可以在 asp 中设置虚拟值:纬度和经度标签,然后用它们填充一个字符串,我可以在谷歌地图中使用。

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

这行得通,当我尝试使用从 json 回调中获得的值时,即使我在使用 console.log() 时可以看到这些值,但它们不起作用。

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

我试过而不是直接阅读添加回 asp:Label 的然后阅读,但是它也不起作用。

我做错了什么?当我玩弄 googlemaps api 时,我试图不为此增加任何复杂性,但这不起作用让我感到困惑,因为我看不出虚拟值与我从 api 获得的值有什么不同。

下面是我在这个页面的所有代码。

<%@ 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>

【问题讨论】:

    标签: javascript html asp.net google-maps api-design


    【解决方案1】:

    你的问题是由于事情发生的时间

    您的 getJSON 调用启动,然后将在未来某个时间点返回数据响应,但是您的其余代码(ISS 值无效)将立即执行

    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)
    

    以上是解决方案的第一步,在 getJSON 调用之前创建地图和标记,并在获得 JSON 响应时更新标记位置。

    另外我会注意到您使用的不是漂亮的 JavaScript 和 JQuery 的混合体

    【讨论】:

    • 我不知道这个。有没有办法让它等待?
    • 现在有更完整的解决方案
    • 一些小错误,变量名不匹配,但确实解决了我的问题。谢谢你。值得添加 map.setCenter(ISS);还有 ISS lng -> lon 下面的解决方案也提供了一些很大的改进,但是鉴于您首先回答,我将此作为最佳答案,因为两者都是有效的,但我觉得您的解决方案稍微更完整。
    • 不用担心 - 我在工作,所以无法以任何方式测试我的答案
    • 我的示例基于您的代码,但如果我正在编写它,我也会使用 ES6 而不是“传统”JavaScript
    【解决方案2】:

    看来您对 JS API 调用有些了解。 当您调用 $.getJSON 时,您有回调方法,该方法将在加载数据时产生结果。 因此,当您创建标记时,您没有定义 IIS 纬度/经度坐标。 关于 JS 你必须知道的另一件有趣的事情 - JS 是一种同步语言,所以你的回调将在所有操作完成后执行(你的脚本的最后一行 - marker.position = ISS; )。 只需在 $.getJSON 回调中创建一个标记即可使其工作

    我创建了一个工作演示,它修复了一些其他存在的错误。

    这里显示起始位置 - 您必须将坐标转换为数字类型:

    function initMap() {
                // The location of ISS
                $.getJSON('http://api.open-notify.org/iss-now.json?callback=?', function (data) {
                    ISS = new google.maps.LatLng(Number(data.iss_position.latitude), Number(data.iss_position.longitude)); 
                    console.log("latitude: " + data['iss_position']['latitude'] + " & longitude: " + data['iss_position']['longitude']);
                    document.getElementById('lblLat').value = data['iss_position']['latitude'];
                    document.getElementById('lblLong').value = 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
                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)
                    }
                });
    
                });   
            }
    

    移动标记代码(使用谷歌类定位新的 google.maps.LatLng):

    function moveISS() {
                $.getJSON('http://api.open-notify.org/iss-now.json?callback=?', function (data) {
                    ISS = new google.maps.LatLng(Number(data.iss_position.latitude), Number(data.iss_position.longitude)); 
                    document.getElementById('lblLat').value = data.iss_position.latitude;
                    document.getElementById('lblLong').value = data.iss_position.longitude;
                    marker.setPosition(ISS);
                    map.setCenter(ISS);
                });
    
                setTimeout(moveISS, 5000);
            } 
    

    http://jsfiddle.net/cheaterr/41h7tmqb/11/

    【讨论】:

    • 我会测试一下,谢谢你的解释。我很少用 Javascript 做任何事情,事实上我这样做是为了学习我不经常使用的东西。感谢改进后的代码,当我尝试不同的方法让它工作时,我的代码变得有点混乱。
    • 我对此进行了测试,并进行了一些调整以适应它,效果很好,我感谢您为给出答案所付出的时间和精力。我会努力改进我的问题和理解。谢谢你:)
    • 不客气。在 JSFiddle 中准备一些解决方案以获得快速答案的最佳方法,因为要确保必须调试代码。
    • 我会查找 JSFiddle。我对 javascript 很陌生,我在大学的大部分时间都设法避免了它。现在我想学习它,我很感激被指出了正确的方向。现在不知道把我的小项目带到哪里去。可能会查找其他一些 api,看看我是否可以结合数据在地图上显示一些有趣的东西。
    猜你喜欢
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多