在Google地图API V3中如何使用if条件检查两个LatLng值?

5

我使用DirectionsRenderer开发了一张带有路线的地图......如果起点和终点在同一位置,我需要让目标标记弹跳......但是当我使用IF检查两个LatLng值是否相同时,程序不会执行IF语句......目标标记无法弹跳......我的编码如下:

        var myOptions = 
    {
        center: new google.maps.LatLng(default_latitude,default_longitude),
        zoom: 4,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("map"),myOptions);
    var latlng1=new google.maps.LatLng(glat,glon);
    var latlng2=new google.maps.LatLng(hlat,hlon);

    var marker = new google.maps.Marker({   
            icon: "http://www.googlemapsmarkers.com/v1/B/67BF4B/000000/00902C/", 
            position: new google.maps.LatLng(glat,glon),
            map: map
        });


    var marker1 = new google.maps.Marker({
                icon: " http://www.googlemapsmarkers.com/v1/A/67BF4B/000000/00902C/", 
                position: new google.maps.LatLng(hlat,hlon),
                map: map

            });  

    //THIS IF STATEMENT IS NOT WORKING ... WHAT CAN I USE INSTEAD OF THIS 
        if(latlng1==latlng2)
            marker1.setAnimation(google.maps.Animation.BOUNCE); 



    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("panel"));
    var request = {
      origin: latlng1,
      destination:latlng2,
      travelMode: google.maps.DirectionsTravelMode.DRIVING
      };

    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
       }
    }); 
2个回答

21

但是,如果你想要检查附近的位置,你可以使用@geocodezip的方法。 - Kris
好的,朋友,那显然是一个经过精细调整的解决方案。将来会在非常微小的地图API中使用geocodezip的代码。感谢你们两个的支持。 - Ree

6

要判断2个google.maps.LatLng对象是否为同一地点,请选择一个距离(例如0.1米),计算它们之间的距离,如果距离小于阈值,则假定它们是同一位置。比较对象只有在它们是相同的完全相同的对象时才会返回 true。比较 2 个浮点数存在问题,而比较两对浮点对象则更加困难。

var SameThreshold = 0.1;
if (google.maps.geometry.spherical.computeDistanceBetween(latlng1,latlng2) < SameThreshold)
   marker1.setAnimation(google.maps.Animation.BOUNCE); 

请务必包含几何库


您的代码也可以工作,先生...但是Krisl的代码更简单...感谢您的支持...希望将来我的问题也能得到同样的帮助... - Ree
+1 @geocodezip 提供了更好的解决方案来检查附近位置。谢谢 - Kris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接