Extend Google Maps marker to animate smoothly on update?

前端 未结 3 812
灰色年华
灰色年华 2020-12-13 00:36

Using the Google Maps API v3 I\'ve been able to update multiple positions of markers via an AJAX call. However, it lacks any transition. Code below:

if ( !la         


        
3条回答
  •  借酒劲吻你
    2020-12-13 01:16

    I did not find any native way to create this animation. You can create your own animation by stepping the position from the current point to the final point using the setPosition. Here is a code snippet to give you an idea:

    var map = undefined;
    var marker = undefined;
    var position = [43, -89];
    
    function initialize() {
    
        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);
        }
    }
    

    This can probably be cleaned up a bit, but will give you a good start. I am using JavaScript's setTimeout method to create the animation. The initial call to 'transition' gets the animation started. The parameter to 'transition' is a two element array [lat, lng]. The 'transition' function calculates the step sizes for lat and lng based upon a couple of animation parametes (numDeltas, delay). It then calls 'moveMarker'. The function 'moveMarker' keeps a simple counter to indicate when the marker has reached the final destination. If not there, it calls itself again.

    Here is a jsFiddle of the code working: https://jsfiddle.net/rcravens/RFHKd/2363/

    Hope this helps.

    Bob

提交回复
热议问题