【发布时间】:2019-11-20 10:14:09
【问题描述】:
我正在创建一个网络应用程序,该应用程序显示离用户当前位置最近的位置和要走的路线。问题是我正在使用一个简单的圆圈动画来显示地图中的用户位置,并且每次用户的位置发生变化时,它都会创建一个新的圆圈。
var circle;
var smallCircle;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
} else {
alert("Sorry the geolocation failed");
}
}
function showPosition(position) {
const pos =
{
lat: position.coords.latitude,
lng: position.coords.longitude
};
console.log(pos);
locationMarker(pos);
}
function locationMarker(user){
if (smallCircle != null & circle != null) {
circle.setCenter(user);
smallCircle.setCenter(user);
map.panTo(user);
} else {
smallCircle = new google.maps.Circle({
center: user,
radius: 5,
strokeColor: "#1abc9c",
strokeOpacity: 1,
strokeWeight: 1,
fillColor: "#1abc9c",
fillOpacity: 0.5
});
circle = new google.maps.Circle({
center: user,
radius: 20,
strokeColor: "#1abc9c",
strokeOpacity: 1,
strokeWeight: 1,
fillColor: "#1abc9c",
fillOpacity: 0.5
});
circle.setMap(map);
smallCircle.setMap(map);
// This is the animation
var direction = 0.8;
var rMin = 5, rMax = 20;
setInterval(function() {
var radius = circle.getRadius();
if ((radius > rMax) || (radius < rMin)) {
direction *= -1;
}
circle.setRadius(radius + direction * 0.4);
}, 50);
}
}
我尝试了一个 if 语句来声明,如果已经有一个圆,它应该改变它的中心(位置)。否则,它应该创建一个新的。
我希望只创建一个圆圈动画,并且每次用户更改其位置时它都可以重新居中,但现在它在更改位置时创建一个新圆圈。
*更新 现在我已经从它正在工作的函数中删除了圆参数。 :)
【问题讨论】:
-
您的代码中有错字:
locationMarker(pos)应该是您调用它的locationMarker(pos, circle, smallCircle)。使用您当前的代码circle和smallCircle将始终为空。 -
谢谢你我已经用你的反馈更新了它,但同样的问题一直在发生。
标签: javascript google-maps-api-3 geolocation google-maps-markers directions