javascript 添加标记和折线到谷歌Map与事件,触发器模仿点击工作不同于实际点击

kfgdxczn  于 2022-12-25  发布在  Java
关注(0)|答案(1)|浏览(119)

我正在尝试使用google.maps.DirectionsService和google.maps.Polyline更新谷歌Map。Map可能在初始化时为空,或者以数组中的坐标开始。
当Map为空时,用户单击的每个位置都将成为一个标记,并且在标记之间将绘制折线路径,并且该路径将随着用户删除标记而调整。
当在手动鼠标单击时使用click事件处理程序时,所有这些都可以很好地工作。
问题是当我试图用数组中的坐标创建的标记填充Map时,我试图简单地将标记latlng坐标放入一个数组中,然后迭代数组,就像有人在单击Map一样。
我尝试了用与单击相同的代码迭代数组,甚至迭代数组以模拟单击事件,调用与单击Map相同的函数。
出于某种原因,当我手动点击时,代码就像我预期的那样运行;当我在数组中迭代运行时,代码的顺序不知何故被打乱了,标记显示出来,但折线路径绘制了太多的线,连接了太多的点。
除了非常简单的DOM操作之外,我对JavaScript还是个新手,所以我怀疑它与谷歌MapAPI使用的异步函数有关,我并不完全理解。我试着在我能想到的地方使用"wait"。我不确定我是否正确地使用了它们,但就像我说的,当我点击Map时,它就能工作。
考虑到数组可能太快了,API跟不上,我在迭代之间放入了一个计时器来减慢它的速度,但结果仍然不同。
下面是代码。

<!DOCTYPE html>
<html>
<head>
  <style>
    #map {height: 600px;width: 100%;}
    .log {margin: 0 0 0 0;padding: 0 0 0 0;}
  </style>
</head>
<body>
  <div id="map"></div>
  <button id="delete-marker">Delete Marker</button>
  <pre id="markersAndPaths"></pre>
  <div id="log"></div>
  <script>

    let map;
    let polyline;
    let directionsService;
    let markers = [];
    let sections = [];
    let fullPath = []; 
    var start = new Date().getTime();
    let default_markers = [
        [36.92137740132106, 138.44167498874666],
        [36.9201679950352, 138.44216315078737],
        [36.92008222081132, 138.43934683132173],
    ]
    function initMap() {
        mapOptions = {
            center: { lat: 36.921, lng: 138.443 },
            zoom: 17,
            scrollwheel: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map'), mapOptions);

        directionsService = new google.maps.DirectionsService();
        polyline = new google.maps.Polyline();
        let debug;
        //debug = 1000;
    if (debug > 0) {
        
        for (var i = 0; i < default_markers.length; i++) {
            var position = new google.maps.LatLng(default_markers[i][0], default_markers[i][1]);
            var marker = new google.maps.Marker({
                 position: position,
                 map: map
            });
            map.setCenter(marker.getPosition());
            map.panTo(map.getCenter());
            markers.push(marker);
            marker.id = markers.length
            
            if (markers.length > 1) {
                doclog(`call polyline m${markers.length}: s${sections.length}`)
                updatePolyLine();
                doclog(``, 'hr')
            }
        }
    }

        map.addListener('click', function(event) {
            var marker = new google.maps.Marker({
                position: event.latLng,
                map: map
            });
            doclog(`markers.length: ${markers.length} event.latlng:${event.latLng}`)
            map.setCenter(marker.getPosition());
            map.panTo(map.getCenter());
            markers.push(marker);
            marker.id = markers.length
            if (markers.length > 1) {
                doclog(`call polyline  m${markers.length}: s${sections.length}`)
                updatePolyLine();
                doclog(``, 'hr')
            }
        });
        
        for (var x = 0; x < default_markers.length; x++) {
            const latLng = new google.maps.LatLng(default_markers[x][0], default_markers[x][1]);
            google.maps.event.trigger(map, 'click', {latLng: latLng});
            //while (new Date().getTime() < start + 1000);  
        }

        document.getElementById('delete-marker').addEventListener('click', function(event) {
            var undone = markers.pop();
            if (markers.length > 0) {
                map.setCenter(markers[markers.length-1].getPosition());
                map.panTo(map.getCenter());
            }
            sections.pop();
            sections.pop();
            undone.setMap(null);
            if (markers.length > 0) {
                updatePolyLine();
            }
        });
    }

    async function updatePolyLine() {
        fullPath = [];
        doclog(`Insdie updatePolyLine: Markers: ${markers.length}`)
        for (var i = 1; i < markers.length; i++) {
            doclog(`${i} < ${markers.length} (i < maerkers.length)`)
            console.log(`${i} < ${markers.length}`);
            if (i == markers.length - 1) {

                doclog(`${i} == ${markers.length - 1} (i == markers.length - 1)`)
                var start = markers[i-1].getPosition()
                var end = markers[i].getPosition()
                var section_id = `${markers[i-1].id}-${markers[i].id}`;
                let section = {
                        'id': section_id,
                        'start_id': markers[i-1].id,
                        'start': start,
                        'end_id': markers[i].id,
                        'end': end,
                        'waypoints': []
                    }
                sections.push(section);
                doclog(`sections.push(${section.id}); sections.length ${sections.length} (i == markers.length - 1)`)
             }  
        }

        for (var i = 0; i < (sections.length); i++) {
            doclog(` .   Inside sections loop: ${i} < ${sections.length}: (i < (sections.length))`)
            doclog(`id = ${sections[i].id} of ${sections.length}`)
            if (sections[i].waypoints == '') {
                await getRoute(sections[i], sections[i].start, sections[i].end)
            } 
            doclog(` .   ----- push to fullpath ------`)
            fullPath.push(sections[i].waypoints);
        }
                
        polyline.setPath(fullPath.flat());
        polyline.setMap(map)

        logMarkersAndSections()
        
        function updateSection(response, section) {
            var path = []
            for (var i = 0, len = response.routes[0].overview_path.length; i < len; i++) {
                path.push(response.routes[0].overview_path[i]);
                console.log(`start_id ${section.start_id} ${response.routes[0].overview_path[i]}`)
            }
            section.waypoints = path;
        }

        async function getRoute(section, start, end) {
            doclog(`Call getRoute sections[${i}](${sections[i]}, ${sections[i].start},${sections[i].end})`)
            var routeOptions = {
                    origin: section.start,
                    destination: section.end,
                    travelMode: 'DRIVING'
            }
            await directionsService.route(routeOptions)
                .then(async function(response) {
                   await updateSection(response, section);
            });   
            doclog(`GOT Route sections[${i}](${sections[i]}, ${sections[i].start},${sections[i].end})`)
                
        };  
    };

    window.initMap = initMap;
  </script>



<script>

    function doclog(data, tag) {
        var stack = new Error().stack;
        var lines = stack.split('\n');
        var lineNumber = lines[2].match(/(\d+):(\d+)/);;
        tag ||= 'p';
        var div = document.getElementById("log");
        var element = document.createElement(tag);
        element.classList.add("log");
        element.innerHTML = (`[${lineNumber[0]}] ${data}`);
        div.appendChild(element);
    }

    function logFullPath() {
        out = `${fullPath}`
        document.getElementById("fullPath").innerHTML = out.replace(/,\(/g, ",\n(");
    }

    function logMarkersAndSections() {
        out = `markers<br>`;
        for (var i = 0; i < markers.length; i++) {
            out += `[${i}] : ${markers[i].position}<br>`
        }
        out += `Sections<br>`;
        for (var i = 0; i < sections.length; i++) {
            out += `[${i}] : (${sections[i].id}) : ${sections[i].start} -> ${sections[i].end}<br>`
        }
        document.getElementById("markersAndPaths").innerHTML = out;
    }

  </script>

<script async defer
src="https://maps.googleapis.com/maps/api/js?key=[apikey]&callback=initMap">
</script>
</body>
</html>

以下是我获得的一些日志记录。第一个日志记录是当我使用click事件通过鼠标单击来手动单击Map上的三个点时:

markers
[0] : (36.921849150345615, 138.442817609787)
[1] : (36.92006506595496, 138.4419914894104)
[2] : (36.919876362280334, 138.44024805355073)
Sections
[0] : (1-2) : (36.921849150345615, 138.442817609787) -> (36.92006506595496, 138.4419914894104)
[1] : (2-3) : (36.92006506595496, 138.4419914894104) -> (36.919876362280334, 138.44024805355073)
[67:13] markers.length: 0 event.latlng:(36.921849150345615, 138.442817609787)
[67:13] markers.length: 1 event.latlng:(36.92006506595496, 138.4419914894104)
[76:17] call polyline m2: s0
[105:9] Insdie updatePolyLine: Markers: 2
[107:13] 1 < 2 (i < maerkers.length)
[111:17] 1 == 1 (i == markers.length - 1)
[124:17] sections.push(1-2); sections.length 1 (i == markers.length - 1)
[129:13] . Inside sections loop: 0 < 1: (i < (sections.length))
[130:13] id = 1-2 of 1
[154:13] Call getRoute sections[0]([object Object], (36.921849150345615, 138.442817609787),(36.92006506595496, 138.4419914894104))
[78:17
[164:13] GOT Route sections[0]([object Object], (36.921849150345615, 138.442817609787),(36.92006506595496, 138.4419914894104))
[134:13] . ----- push to fullpath ------
[67:13] markers.length: 2 event.latlng:(36.919876362280334, 138.44024805355073)
[76:17] call polyline m3: s1
[105:9] Insdie updatePolyLine: Markers: 3
[107:13] 1 < 3 (i < maerkers.length)
[107:13] 2 < 3 (i < maerkers.length)
[111:17] 2 == 2 (i == markers.length - 1)
[124:17] sections.push(2-3); sections.length 2 (i == markers.length - 1)
[129:13] . Inside sections loop: 0 < 2: (i < (sections.length))
[130:13] id = 1-2 of 2
[134:13] . ----- push to fullpath ------
[129:13] . Inside sections loop: 1 < 2: (i < (sections.length))
[130:13] id = 2-3 of 2
[154:13] Call getRoute sections[1]([object Object], (36.92006506595496, 138.4419914894104),(36.919876362280334, 138.44024805355073))
[78:17]
[164:13] GOT Route sections[1]([object Object], (36.92006506595496, 138.4419914894104),(36.919876362280334, 138.44024805355073))
[134:13] . ----- push to fullpath ------

第二个例子是当我迭代default_array调用google. maps. event. trigger(Map,'点击',{latLng:(单位:lng});
在手动点击的标记检索Route Section并将其推入fullpath []之前,一切都是相同的。迭代的标记跳过该操作并调用updatePolyLine()函数。

markers
[0] : (36.92137740132106, 138.44167498874666)
[1] : (36.9201679950352, 138.44216315078737)
[2] : (36.92008222081132, 138.43934683132173)
Sections
[0] : (1-2) : (36.92137740132106, 138.44167498874666) -> (36.9201679950352, 138.44216315078737)
[1] : (2-3) : (36.9201679950352, 138.44216315078737) -> (36.92008222081132, 138.43934683132173)
[67:13] markers.length: 0 event.latlng:(36.92137740132106, 138.44167498874666)
[67:13] markers.length: 1 event.latlng:(36.9201679950352, 138.44216315078737)
[76:17] call polyline m2: s0
[105:9] Insdie updatePolyLine: Markers: 2
[107:13] 1 < 2 (i < maerkers.length)
[111:17] 1 == 1 (i == markers.length - 1)
[124:17] sections.push(1-2); sections.length 1 (i == markers.length - 1)
[129:13] . Inside sections loop: 0 < 1: (i < (sections.length))
[130:13] id = 1-2 of 1
[154:13] Call getRoute sections[0]([object Object], (36.92137740132106, 138.44167498874666),(36.9201679950352, 138.44216315078737))
[78:17
[67:13] markers.length: 2 event.latlng:(36.92008222081132, 138.43934683132173)
[76:17] call polyline m3: s1
[105:9] Insdie updatePolyLine: Markers: 3
[107:13] 1 < 3 (i < maerkers.length)
[107:13] 2 < 3 (i < maerkers.length)
[111:17] 2 == 2 (i == markers.length - 1)
[124:17] sections.push(2-3); sections.length 2 (i == markers.length - 1)
[129:13] . Inside sections loop: 0 < 2: (i < (sections.length))
[130:13] id = 1-2 of 2
[154:13] Call getRoute sections[0]([object Object], (36.92137740132106, 138.44167498874666),(36.9201679950352, 138.44216315078737))
[78:17]
[164:13] GOT Route sections[0]([object Object], (36.92137740132106, 138.44167498874666),(36.9201679950352, 138.44216315078737))
[134:13] . ----- push to fullpath ------
[129:13] . Inside sections loop: 1 < 2: (i < (sections.length))
[130:13] id = 2-3 of 2
[154:13] Call getRoute sections[1]([object Object], (36.9201679950352, 138.44216315078737),(36.92008222081132, 138.43934683132173))
[164:13] GOT Route sections[0]([object Object], (36.92137740132106, 138.44167498874666),(36.9201679950352, 138.44216315078737))
[134:13] . ----- push to fullpath ------
[129:13] . Inside sections loop: 1 < 2: (i < (sections.length))
[130:13] id = 2-3 of 2
[154:13] Call getRoute sections[1]([object Object], (36.9201679950352, 138.44216315078737),(36.92008222081132, 138.43934683132173))
[164:13] GOT Route sections[1]([object Object], (36.9201679950352, 138.44216315078737),(36.92008222081132, 138.43934683132173))
[134:13] . ----- push to fullpath ------
[164:13] GOT Route sections[1]([object Object], (36.9201679950352, 138.44216315078737),(36.92008222081132, 138.43934683132173))
[134:13] . ----- push to fullpath ------
zpgglvta

zpgglvta1#

在Map上触发"单击"事件后,给浏览器一段时间来请求、接收和呈现方向段:

for (var x = 0; x < default_markers.length; x++) {
    const latLng = new google.maps.LatLng(default_markers[x][0], default_markers[x][1]);
    setTimeout(function() {
        google.maps.event.trigger(map, 'click', {latLng: latLng});
    },1000*x);  // 1 second between clicks
}

proof of concept fiddle

    • 代码片段:**

x一个一个一个一个x一个一个二个一个x一个一个三个一个

相关问题