【问题标题】:How to use Google Maps with PubNub in Angular如何在 Angular 中将 Google 地图与 PubNub 一起使用
【发布时间】:2020-05-29 07:09:56
【问题描述】:

我正在尝试使用 PubNub 在我的应用程序中实现跟踪系统。我通过更改 Angular.json 文件中的配置使用 Javascript 创建了 Google 地图。我正在调用一个外部 javascript 文件。

我无法在我的 Angular 应用程序中显示地图,但是当我在普通 HTML 中使用相同的代码时,它可以正常工作。但是当我在我的 Angular 应用程序中添加相同的代码时,地图并没有显示出来。

HTML:

   <script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.19.0.min.js"></script>


   <div class="container">
    <h1>PubNub Google Maps - Live Device Location</h1>
    <div id="map" style="width:100%;height:600px"></div>
  </div>

JS:

             window.lat = 28.7041;
             window.lng = 77.1025;

            function getLocation() {
                if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(updatePosition);
              }

           return null;
           };

          function updatePosition(position) {
           if (position) {
             window.lat = position.coords.latitude;
            window.lng = position.coords.longitude;
           }
          }

          setInterval(function(){updatePosition(getLocation());}, 20000);

         function currentLocation() {
            return {lat:window.lat, lng:window.lng};
         };

        var map;
        var mark;
        var lineCoords = [];
        var initialize = function() {
        var icon = {
           url: "assests/images/download.png", // url
           scaledSize: new google.maps.Size(30, 30), // scaled size
           origin: new google.maps.Point(0,0), // origin
          anchor: new google.maps.Point(0, 0) // anchor
        };

       map  = new google.maps.Map(document.getElementById('map-canvas'), {center:  {lat:lat,lng:lng},zoom:12});
       mark = new google.maps.Marker({position:{lat:lat, lng:lng}, map:map,
      icon: icon
      });

    };
    window.initialize = initialize;

    var redraw = function(payload) {
        lat = payload.message.lat;
        lng = payload.message.lng;
        map.setCenter({lat:lat, lng:lng, alt:0});
        mark.setPosition({lat:lat, lng:lng, alt:0});
        lineCoords.push(new google.maps.LatLng(lat, lng));
        var lineCoordinatesPath = new google.maps.Polyline({
          path: lineCoords,
          geodesic: true,
          strokeColor: '#FF0000'
        });
        lineCoordinatesPath.setMap(map);
      };

    var pnChannel = "map-channel";

    var pubnub = new PubNub({
      publishKey:   'pub-c-redacted',
      subscribeKey: 'sub-c-redacted'
    });

    pubnub.subscribe({channels: [pnChannel]});
    pubnub.addListener({message:redraw});

    setInterval(function() {
        pubnub.publish({channel:pnChannel, message:{lat:window.lat + 0.001, lng:window.lng + 0.01}});
      }, 10000);

面对错误:

 Uncaught TypeError: Cannot read property 'setCenter' of undefined

【问题讨论】:

    标签: angular pubnub


    【解决方案1】:

    透明度:我在 PubNub 工作,但我不太了解 Google 地图。 我想在 cmets 中提出一些问题,但在您的代码中发现了一些潜在的错误,因此在此处添加作为 潜在 答案并尝试使用新代码。这段代码在整个过程中都有解决潜在错误的 cmets。如果您有任何疑问或者这是否解决了您的问题,请发表评论。

    我还添加了额外的 HTML 标记,例如 &lt;head&gt;&lt;body&gt;,并将所有脚本/代码移至 &lt;body&gt; 标记下方。这可能是也可能不是你需要做的,但无论如何都应该工作。

    <html>
    <head>
    <title>PubNub & Google Maps</title>
    </head>
    
    <body>
    <div class="container">
        <h1>PubNub Google Maps - Live Device Location</h1>
    
        <!-- You used "map" as your id here: 
        <div id="map" style="width:100%;height:600px"></div>
        ... but down in your code you getElementById('map-canvas')
        Shouldn't this id be "map-canvas"? That might be why it doesn't display.
        -->
        <div id="map-canvas" style="width:100%;height:600px"></div>
    </div>
    </body>
    
    <!-- I don't have the index.js file so I couldn't properly test your code -->
    <script src="./assests/js/index.js"></script>
    
    <!-- PubNub JS SDK v4.19.0 is pretty old. You should use the latest version of PubNub JS SDK - v4.27.6 -->
    <!-- script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.19.0.min.js"></script> -->
    <script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.27.6.min.js"></script>
    
    <!-- added this script tag and the closing script tag at the end of this code -->
    <script type="text/javascript">
    window.lat = 28.7041;
    window.lng = 77.1025;
    
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(updatePosition);
        }
    
        return null;
    };
    
    function updatePosition(position) {
        if (position) {
            window.lat = position.coords.latitude;
            window.lng = position.coords.longitude;
        }
    }
    
    setInterval(function(){updatePosition(getLocation());}, 20000);
    
    function currentLocation() {
        return {lat:window.lat, lng:window.lng};
    };
    
    var map;
    var mark;
    var lineCoords = [];
    var initialize = function() {
        var icon = {
            url: "assests/images/download.png", // url
               scaledSize: new google.maps.Size(30, 30), // scaled size
               origin: new google.maps.Point(0,0), // origin
              anchor: new google.maps.Point(0, 0) // anchor
          };
    
    
          // this is where you do getElementById('map-canvas') 
          // but the id in the `<body>` was `map`
          // I suspect the variable here should be `map` but the id above should
          // be `map-canvas` and that is probably why you get that
          // error when you call `map.setCenter`
          map  = new google.maps.Map(document.getElementById('map-canvas'), {center:  {lat:lat,lng:lng},zoom:12});
          mark = new google.maps.Marker({position:{lat:lat, lng:lng}, map:map,
            icon: icon
          });
    
      };
      window.initialize = initialize;
    
      var redraw = function(payload) {
        lat = payload.message.lat;
        lng = payload.message.lng;
        map.setCenter({lat:lat, lng:lng, alt:0});
        mark.setPosition({lat:lat, lng:lng, alt:0});
        lineCoords.push(new google.maps.LatLng(lat, lng));
        var lineCoordinatesPath = new google.maps.Polyline({
            path: lineCoords,
            geodesic: true,
            strokeColor: '#FF0000'
        });
        lineCoordinatesPath.setMap(map);
      };
    
      var pnChannel = "map-channel";
    
      // redacted your keys - do not share with public
      var pubnub = new PubNub({
        publishKey:   'pub-c-redacted',
        subscribeKey: 'sub-c-redacted'
      });
    
      // switched the order of these two lines of code
      // you should addListener first, then subscribe
      pubnub.addListener({message:redraw});
      pubnub.subscribe({channels: [pnChannel]});
    
      setInterval(function() {
        pubnub.publish({channel:pnChannel, message:{lat:window.lat + 0.001, lng:window.lng + 0.01}});
      }, 10000);
    
    // here's the ending script tag I added that I mentioned above
    </script>
    </html>
    

    我知道 PubNub 代码修复/建议是正确的。让我知道我对 html/javascript/google 地图问题是否正确。我无法完全测试您的代码,因为我没有您的 assests/js/index.js 代码文件。

    【讨论】:

    • 您还可以从查看以JS quickstart 开始的新 PubNub 平台文档中受益。但一定要跳到关于频道的部分。它应该让您快速学习使用 PubNub。但我怀疑这比 PubNub 更像是一个 Angular 问题。
    • 假设您的代码来自 pubnub.com/blog/javascript-mapping-javascript-tracking - 我在上面的代码中没有看到 googleapis 库脚本。假设它在您的index.js 代码文件中?
    • 是的,现在我正在查看教程系列中的代码,我发现您应该在div 标签中使用map-canvas 作为id
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 2017-06-27
    • 2011-10-12
    相关资源
    最近更新 更多