【问题标题】:Map on click to get multiple coordinates点击地图获取多个坐标
【发布时间】:2015-03-09 20:55:33
【问题描述】:

我在尝试在地图上绘制两个标记并获取开始和结束坐标时遇到了一些问题。代码如下:

function showBusFilter(){
 map.on("click", function (evt) { 
     var counter = 1;
     if(counter == 1){
         var startLoc = (evt.mapPoint.x, evt.mapPoint.y);
         counter++;
     }
     else if(counter == 2){
         var endLoc = (evt.mapPoint.x, evt.mapPoint.y);
         counter = 1;
     }
     console.log(startLoc);
     console.log(endLoc);
     plotBusRouteByMarker(startLoc, endLoc);
 });    
}

我正在使用计数器变量来区分第一个和第二个标记。所以基本上我想做的是当第一次点击地图时,我得到了 startLoc。然后,当地图第二次点击时,我得到了 endLoc。在得到它们之后,我将它们作为路由方法的参数传递。

但是,使用这些代码,当我点击地图时,它只会用坐标填充 startLoc,用 undefined 填充 endLoc 并执行 plotBusRouteByMarker()。

有什么想法吗?

提前致谢。

【问题讨论】:

    标签: java javascript maps arcgis esri


    【解决方案1】:

    这是因为每当您单击地图时,“counter”变量始终为 1,因此每次都会分配 startLoc。
    您可以改为借助 closure 概念来记住如下所示的“counter

    var counter = 0;
    
    function showBusFilter() {
        map.on("click", function(evt) {//anonymous fn
                counter ++ ;//now this will point to global counter and hence will not claimed by GC after fn execution
                if(counter === 1) {
                    var startLoc = (evt.mapPoint.x, evt.mapPoint.y);
                } else if(counter === 2) {
                    var endLoc = (evt.mapPoint.x, evt.mapPoint.y);
                    counter = 0;
                }
                plotBusRouteByMarker(startLoc, endLoc);
            });
    }
    

    【讨论】:

    • 我明白了。此外,变量 startloc 和 endloc 的声明应该在 map onclick 函数之外。否则,每次点击地图时,之前的值都会被清除:)
    猜你喜欢
    • 2011-06-21
    • 2013-05-15
    • 2011-05-09
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 1970-01-01
    • 2011-09-29
    相关资源
    最近更新 更多