2012-09-10 35 views
0

我的代碼:谷歌地圖API watchPosition

var watchID; 
     var geoLoc; 

     var geoService = navigator.geolocation; 
     if (geoService) { 
      geoService.getCurrentPosition(showCurrentLocation,errorHandler,{enableHighAccuracy: true}); 
     } else { 
      alert("Your Browser does not support GeoLocation."); 
     } 

     function showCurrentLocation(position){ 
      var latLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); 

      //Google Map options 
      var myOptions = {zoom: 16, 
          center: latLng, 
          mapTypeId: google.maps.MapTypeId.ROADMAP 
          }; 

      var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 

      var usermarker = new google.maps.Marker({position: latLng, map: map, title: "You are here!"}); 

      map.setCenter(latLng); 
      usermarker.setPosition(latLng); 
      getLocationUpdate(usermarker, latLng) 
     } 

     function errorHandler(error){ 
       alert("Error while retrieving current position. Error code: " + error.code + ",Message: " + error.message); 
     } 

     function getLocationUpdate(usermarker, latLng){ 
      if(navigator.geolocation){ 
       var options = {timeout:60000}; 
       geoLoc = navigator.geolocation; 
       watchID = geoLoc.watchPosition(showLocation, 
              errorHandler, 
              options); 
      }else{ 
       alert("Sorry, browser does not support geolocation!"); 
      } 
     } 

     function showLocation(position){ 
      op = document.getElementById("output"); 
      var latitude = position.coords.latitude; 
      var longitude = position.coords.longitude; 

      op.innerHTML = "Latitude : " + latitude + "<br />Longitude: " + longitude; 
     } 

其中規定了地圖,並得到我的當前位置。我正試圖讓地圖居中並移動標記。 getLocationUpdate當前會觸發watchLocation,但我不知道如何更新標記和地圖中心。

任何幫助表示讚賞。

+0

做你設法找到一個解決辦法? –

回答

0

試試這個:

map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));

它集中了 「移動地圖」 ......

0

您設置的位置在一個錯誤的方式標記,請嘗試:

position: new google.maps.LatLng(latLng) 

,您可以更新標記的位置:

newLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); 
marker.setPosition(newLatlng); 

稱爲內showLocation(位置)

希望它可以幫助...