我使用JavaScript和Google Maps API编写了一个小型手持设备应用程序,现在我需要使用计时器函数沿着一条路线在地图上随意移动我的标记图标。 我有一个人的图标,并且需要自动在地图上移动它。 我该如何做到这一点?
我使用JavaScript和Google Maps API编写了一个小型手持设备应用程序,现在我需要使用计时器函数沿着一条路线在地图上随意移动我的标记图标。 我有一个人的图标,并且需要自动在地图上移动它。 我该如何做到这一点?
很遗憾,官方的GMaps集合中没有自动标记移动功能。
但是,如果您有一个GRoute,那意味着您有一组点。要循环遍历路线步骤,您可以使用类似以下代码:
for (var c = 0; c < yourroute.getNumSteps(); c++) {
yourmarker.setLatLng(yourroute.getStep(c).getLatLng());
}
function moveToStep(yourmarker,yourroute,c) {
if {yourroute.getNumSteps() > c) {
yourmarker.setLatLng(yourroute.getStep(c).getLatLng());
window.setTimeout(function(){
moveToStep(yourmarker,yourroute,c+1);
},500);
}
}
moveToStep(marker,route,0);
我尽可能地简化了它。随意使用。
var autoDriveSteps = new Array();
var speedFactor = 10; // 10x faster animated drive
function setAnimatedRoute(origin, destination, map) {
// init routing services
var directionsService = new google.maps.DirectionsService;
var directionsRenderer = new google.maps.DirectionsRenderer({
map: map
});
//calculate route
directionsService.route({
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
},
function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// display the route
directionsRenderer.setDirections(response);
// calculate positions for the animation steps
// the result is an array of LatLng, stored in autoDriveSteps
autoDriveSteps = new Array();
var remainingSeconds = 0;
var leg = response.routes[0].legs[0]; // supporting single route, single legs currently
leg.steps.forEach(function(step) {
var stepSeconds = step.duration.value;
var nextStopSeconds = speedFactor - remainingSeconds;
while (nextStopSeconds <= stepSeconds) {
var nextStopLatLng = getPointBetween(step.start_location, step.end_location, nextStopSeconds / stepSeconds);
autoDriveSteps.push(nextStopLatLng);
nextStopSeconds += speedFactor;
}
remainingSeconds = stepSeconds + speedFactor - nextStopSeconds;
});
if (remainingSeconds > 0) {
autoDriveSteps.push(leg.end_location);
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
// helper method to calculate a point between A and B at some ratio
function getPointBetween(a, b, ratio) {
return new google.maps.LatLng(a.lat() + (b.lat() - a.lat()) * ratio, a.lng() + (b.lng() - a.lng()) * ratio);
}
// start the route simulation
function startRouteAnimation(marker) {
var autoDriveTimer = setInterval(function () {
// stop the timer if the route is finished
if (autoDriveSteps.length === 0) {
clearInterval(autoDriveTimer);
} else {
// move marker to the next position (always the first in the array)
marker.setPosition(autoDriveSteps[0]);
// remove the processed position
autoDriveSteps.shift();
}
},
1000);
}
使用方法:
setAnimatedRoute("source address or LatLng ...", "destination address or LatLng ...", map);
// start simulation on button click...
$("#simulateRouteButton").click(function() {
startRouteAnimation(agentMarker);
});