如何使用Google Maps API进行流畅的标记移动?

时间:2017-12-07 18:02:32

标签: javascript google-maps

当标记立即改变位置时,我的标记会猛烈地抖动。 Google Maps API中是否有相应的CSS transiton: 1s linear,以便我的标记可以顺利移动? 这是我的地图初始化代码:

var marker;

    function initMap() {
    // Map initialization
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 1,
            center: { lat: 59.325, lng: 18.070 }
        });
    // Marker settings
        marker = new google.maps.Marker({
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: { lat: 59.327, lng: 18.067 }
        });
    // Marker moves every second
        setInterval( () => {
            moveMarker();
        }, 1000);    
    }

    var a = 1;
    function moveMarker() {
        marker.setPosition(new google.maps.LatLng(a++, a++));
    }
#map {
  width: 500px;
  height: 500px;
}
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCJYSNYPAfcm8ZV4pi8nj6fbeOtbQQpr7Y&callback=initMap"></script>

1 个答案:

答案 0 :(得分:1)

它非常可行,但需要工作。重要的是识别谷歌地图用于你的标记的DIV(有两个是触摸事件透明的)调查已经完成,你真的只需要了解一次。

可以找到一个完整的例子here看看Hansel和Gretel在地图上的移动有多顺畅!如果有任何延迟,转换时间会合并。

我的Brotkrumen Ultimate Web App的所有代码都可以找到here你最感兴趣的是HandleMap.js文件,但是有一个aaa_readme.txt

以下是代码的一部分: -

function showJourney(){
    map.setZoom(map.getZoom());
    map.setOptions({gestureHandling: "none"});
    zoomOut.style.display = "none";
    zoomIn.style.display  = "none";

    hat.setPosition(
        new google.maps.LatLng(
                lastPos.coords.latitude,
                lastPos.coords.longitude)); 
    hat.setVisible(true);
    hat.setAnimation(bounce);

    HandG.setPosition(
        new google.maps.LatLng(
                firstPos.coords.latitude,
                firstPos.coords.longitude)); 
    HandG.setVisible(true);

    map.panTo(path[0]); 
    google.maps.event.trigger(map, 'resize');

    if (document.querySelectorAll(MARKER_SELECTOR).length == 0){
        observer.observe(mapDiv, {
                        childList     : true,
                        subtree       : true ,
                        attributes    : true ,
                        characterData : false
                        })
    } else {
        setTimeout(plotTrip,0);
    }
}
function plotTrip(){
    nextFunc = plotStep;
    hat.setAnimation(bounce);
    HandG.setPosition(path[0]);
    dirPoly.setVisible(true);       
    progressPath = [];
    progressPath.push(path[0]);
    dirPoly.setPath(path);
    stepPoly.setPath(progressPath);
    stepPoly.setVisible(true);
    currStep = 1;
    markerDivs = [];
    var markerImgs = document.querySelectorAll(MARKER_SELECTOR);
    for (var i=0; i<markerImgs.length; i++){
        console.log(markerImgs[i].src);
        markerDivs[i] = markerImgs[i].parentNode;
        markerDivs[i].style.transitionDuration = "0s";
        markerDivs[i].style.transitionProperty = "left, top";
        markerDivs[i].style.transitionTimingFunction = "linear";
    }

    setTimeout(plotStep,0);
    abort = false;
    btn.value = "Cancel";
    btn.disabled = false;
}
function plotStep(){
    if (abort) return;

    if (legs[currStep].didLoiter){
        countDown = legs[currStep].restTime;
        infoWindow.setContent(
            "<div id='waitDiv'><span>Waiting</span></div>");
        infoWindow.open(map,HandG);
        showInterval();
    } else {
        plotIt();
    }
}
function showInterval(){
    if (abort) return;

    infoWindow.setContent(
        "<div id='waitDiv'><span>Waiting "+deltaDate(countDown)+"</span></div>");
    countDown -= (ONE_SEC * multiSpeed);
    if (countDown < 1){
        infoWindow.close(); 
        plotIt();
    } else {
        setTimeout(showInterval, ONE_SEC);
    }
}
function plotIt(){
    if (abort) return;

    progressPath.push(path[currStep]);
    stepPoly.setPath(progressPath);
    map.panTo(path[currStep]);
    var transitionMS = legs[currStep].duration / multiSpeed;
    for (var i=0; i<markerDivs.length; i++){
        markerDivs[i].style.transitionDuration = transitionMS + "ms";
    }
    HandG.setPosition(path[currStep])

    if (++currStep >= path.length)
        nextFunc = cleanUp;

    plotTimer = setTimeout(nextFunc,transitionMS);
}
function cleanUp(){
    infoWindow.close();
    hat.setAnimation();
    btn.value = "Replay";
    btn.disabled = false;
    clearTimeout(plotTimer);
    for (var i=0; i<markerDivs.length; i++){
        markerDivs[i].style.transitionDuration = "0s";
    }
    HandG.setPosition(
        new google.maps.LatLng(
                lastPos.coords.latitude,
                lastPos.coords.longitude)); 
    HandG.setVisible(false);
    map.setOptions({gestureHandling: "cooperative"});
    zoomIn.style.display  = "";
    zoomOut.style.display = "";
    if (canTalk && !abort)
        speechSynthesis.speak(finish);
}
function waitForMarker(mutations, myInstance) {
    outer:
    for (var i=0; i<mutations.length; i++){
        if (mutations[i].type           == "attributes" && 
            mutations[i].target.tagName == "IMG"        &&
            mutations[i].target.src.toLowerCase().indexOf(MARKER_SRC) != -1){
            console.log("result")
            myInstance.disconnect();
            setTimeout(plotTrip,0)
            break outer;
        }
        if (mutations[i].type != "childList" ||
            mutations[i].addedNodes.length   == 0) 
            continue;
        for (var j=0; j<mutations[i].addedNodes.length; j++) {
            var node = mutations[i].addedNodes[j];
            if (node.tagName == "DIV" && node.firstChild && node.firstChild.tagName == "IMG" &&
                node.firstChild.src.toLowerCase().indexOf(MARKER_SRC) != -1){
                console.log(node.firstChild.src);
                myInstance.disconnect();
                setTimeout(plotTrip,0)
                break outer;
            }
        }
    }
}