-1

I am using this Script to move the Google Map marker from 1 place to another source Extend Google Maps marker to animate smoothly on update?

As per my logic here the Difference between the Previous & the Current Location is calculated & divided by a number (eg 100) & adding the result to the Previous Location for 100 times to reach the Current Location.

But when I change the Value of steps (Num Deltas) as given below from 100 to any other Number for Eg 4 & make the Loop run 4 times the Location of the Marker after that is different from the Current Location. Can any one plaese suggest me the Importance of using the No. of Steps (Num Deltas) as 100 & not any other Number`

var latlng = new google.maps.LatLng(position[0], position[1]);
var myOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

marker = new google.maps.Marker({
    position: latlng,
    map: map,
    title: "Your current location!"
});

google.maps.event.addListener(map, 'click', function(me) {
    var result = [me.latLng.lat(), me.latLng.lng()];
    transition(result);
});
}

var numDeltas = 100;
var delay = 10; //milliseconds
var i = 0;
var deltaLat;
var deltaLng;
function transition(result){
i = 0;
deltaLat = (result[0] - position[0])/numDeltas;
deltaLng = (result[1] - position[1])/numDeltas;
moveMarker();
}

 function moveMarker(){
position[0] += deltaLat;
position[1] += deltaLng;
var latlng = new google.maps.LatLng(position[0], position[1]);
marker.setPosition(latlng);
if(i!=numDeltas){
    i++;
    setTimeout(moveMarker, delay);
}
}

Here is a jsFiddle of the code working: http://jsfiddle.net/rcravens/RFHKd/13/

Community
  • 1
  • 1

1 Answers1

1

Your problem is this line:

function transition(result){
    i = 0; //<--THIS ONE

you should set it to i = 1;. Currently you are making 1 more move than you should. When dividing the path with 100 it's just not that visible, because the difference is very small but the bug was always there. Alternatively you can change the ending condition.

Matej P.
  • 5,303
  • 1
  • 28
  • 44
  • You are very Correct Exactly this is the Bug but you can check in the JS Fiddle http://jsfiddle.net/rcravens/RFHKd/13/ it is working proerly with i=0; that is making the condition more worse for me & this answer has been marked as the correct answer http://stackoverflow.com/questions/5892113/extend-google-maps-marker-to-animate-smoothly-on-update – Sandeep Oberoi Jun 07 '16 at 17:54
  • Even marked answers could have bugs. and the fiddle you referenced doesn't work correctly, you could see that if you click the map, the marker ends up in a position slightly off than it should. Try to click half a world away. Anyway, Just make `i = 1` in both places. Does it work? – Matej P. Jun 07 '16 at 18:15