地理位置watchPosition。当位置到达时如何获得一个事件?

问题描述:

我正在为移动用户开发一个WebApp,它已经去预定义的位置,并且首先可以看到有一个<div>(文本,图片或其他)。 所以,我有一个预定义的位置和当前的用户位置。如果两个地点都相同,我会展示一些东西。 我该怎么办?这个代码不工作:地理位置watchPosition。当位置到达时如何获得一个事件?

var id, ziel, options; 
//Verfolgen beginnen 
id = navigator.geolocation.watchCurrentPosition(verfolgePosition); 

function verfolgePosition(pos) { 
    var aktuell = pos.coords; 

    if (ziel.latitude === aktuell.latitude && ziel.longitude === aktuell.longitude) { 
    console.log('Sie haben Ihr Ziel erreicht'); 
    //Verfolgen beenden 
    navigator.geolocation.clearWatch(id); 
    } 
} 

ziel = { 
    latitude : 0, 
    longitude: 0 
}; 

options = { 
    enableHighAccuracy: false, 
    timeout: 5000, 
    maximumAge: 0 
}; 

的方式,目标可以是:

ziel = { 
    latitude : 52.514971, 
    longitude: 13.369172 
}; 
+0

没有方法'watchCurrentPosition()'。你正在寻找的是'.watchPosition()'[W3](https://dev.w3.org/geo/api/spec-source.html#watch-position)/ [mdn](https:// developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition) – Andreas

+0

Yes is true。我将它改为'.watchPosition',但它只能使用一次。也许是因为可移动位置(移动设备)快速变化以获得确切的固定位置,同样,如果我在相同位置测试此脚本。我该如何解决它? – kubus1234

+0

从我的评论中的w3链接:“_在手表过程的步骤5.2.2中,只有在获得新位置并且此**位置与先前报告的位置**显着不同时才调用successCallback **。关于什么构成显着差异的定义留待执行。**此外,在步骤5.2.2和5.2.3中,实现可能对回调频率施加限制,以避免不经意地消耗不成比例的资源** ._“ – Andreas

我刚打了一点点我的代码,并重新激活该项目。 现在的问题是if声明。我比较两个值,经度和纬度,但在结果他们不相等。怎么了?

<script> 
    (function() { 

     if(!!navigator.geolocation) { 

      var map, 
       ziel, 
       options; 

      var mapOptions = { 
       zoom: 15, 
       mapTypeId: google.maps.MapTypeId.ROADMAP 
      }; 

      ziel = { 
      latitude : 52.2741, 
      longitude: 8.0317 
      }; 

      options = { 
      enableHighAccuracy: true, 
      timeout: 5000, 
      maximumAge: 0 
      }; 

      map = new google.maps.Map(document.getElementById('google_canvas'), mapOptions); 

      navigator.geolocation.watchPosition(function(position) { 

       var geolocate = new google.maps.LatLng(position.coords.latitude.toFixed(4), position.coords.longitude.toFixed(4)); 
       var ziel = new google.maps.LatLng(52.2741, 8.0317); 

       if (ziel.latitude == position.coords.latitude.toFixed(4) && ziel.longitude == position.coords.longitude.toFixed(4)) { 

       alert("I managed it"); 
       //Verfolgen beenden 
       //navigator.geolocation.clearWatch(id); 
       } 
       else { 

       alert("Fail !!! meine Position "+ geolocate +" Zielposition "+ ziel +""); 

       } 


       var infowindow = new google.maps.InfoWindow({ 
        map: map, 
        position: geolocate, 
        content: 
         '<h1>Location pinned from HTML5 Geolocation!</h1>' + 
         '<h2>Latitude: ' + position.coords.latitude.toFixed(4) + '</h2>' + 
         '<h2>Longitude: ' + position.coords.longitude.toFixed(4) + '</h2>' 
       }); 

       map.setCenter(geolocate); 

      }); 

     } else { 
      document.getElementById('google_canvas').innerHTML = 'No Geolocation Support.'; 
     } 

    })();