【发布时间】: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
【问题讨论】: