简体   繁体   English

如何在 Angular 中将 Google 地图与 PubNub 一起使用

[英]How to use Google Maps with PubNub in Angular

I am trying to implement the tracking system in my application using PubNub.我正在尝试使用 PubNub 在我的应用程序中实现跟踪系统。 I have created the Google map using Javascript by changing the configurations in the Angular.json file.我通过更改 Angular.Z466DEEC76ECDF5FCA654D38571F623 文件中的配置,使用 Javascript 创建了 Google map。 I am calling an external javascript file.我正在调用外部 javascript 文件。

I am not able to display the map in my Angular application, but when I use the same code in normal HTML it is working.我无法在我的 Angular 应用程序中显示 map,但是当我在正常的 HTML 中使用相同的代码时,它正在工作。 But when I added the same code in my Angular application map is not displaying.但是当我在我的 Angular 应用程序中添加相同的代码时,map 没有显示。

HTML: 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: 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);

Error Facing:面对错误:

 Uncaught TypeError: Cannot read property 'setCenter' of undefined

Transparency: I work for PubNub and I don't know Google Maps that well.透明度:我在 PubNub 工作,但我不太了解 Google 地图。 I wanted to ask some questions in comments but found some potential bugs in your code so adding as a potential answer here with new code to try.我想在评论中提出一些问题,但在您的代码中发现了一些潜在的错误,因此在此处添加新代码作为潜在答案以尝试。 This code has comments throughout that address the potential bugs.此代码在整个过程中都有注释,以解决潜在的错误。 Please comment if you have questions or if this solves your issue.如果您有任何疑问或这是否解决了您的问题,请发表评论。

I also added additional HTML markup like <head> and <body> and moved all scripts/code below the <body> tag.我还添加了额外的 HTML 标记,例如<head><body>并将所有脚本/代码移动到<body>标记下方。 That may or may not be what you need to do but should work anyways.这可能是也可能不是您需要做的,但无论如何都应该起作用。

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

I know the PubNub code fixes/recommendations are proper.我知道 PubNub 代码修复/建议是正确的。 Let me know if I was correct about the html/javascript/google maps issues.让我知道我对 html/javascript/google 地图问题是否正确。 I couldn't fully test your code because I don't have your assests/js/index.js code file.我无法完全测试您的代码,因为我没有您的assests/js/index.js代码文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM