2015-07-03 38 views
3

是否有可能使用地理位置同步用户位置?因此,如果用户正在旅行,他的位置将在页面上更新,有些像导航其位置...用java脚本中的google地图同步用户位置

我已经试过这个,但是,整个地图不断刷新,需要时间来加载...它工作正常,但是,有没有更好的方式,我可以跟踪用户的位置?

<script src="https://maps.googleapis.com/maps/api/js"></script> 
    <script src="../dist/geolocationmarker-compiled.js"></script> 
    <script> 
     var map, GeoMarker; 

     setInterval (function initialize() { 
      var mapOptions = { 
       zoom: 17, 
       center: new google.maps.LatLng(-34.397, 150.644), 
       mapTypeId: google.maps.MapTypeId.ROADMAP 
      }; 
      map = new google.maps.Map(document.getElementById('map_canvas'), 
      mapOptions); 

      GeoMarker = new GeolocationMarker(); 
      GeoMarker.setCircleOptions({fillColor: '#808080'}); 

      google.maps.event.addListenerOnce(GeoMarker, 'position_changed',  function() { 
       map.setCenter(this.getPosition()); 
       map.fitBounds(this.getBounds()); 
      }); 

      google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) { 
       alert('There was an error obtaining your position. Message: ' + e.message); 
      }); 
      console.log('updating'); 
      GeoMarker.setMap(map); 
     },10000); 

    google.maps.event.addDomListener(window, 'load', initialize); 

    if(!navigator.geolocation) { 
     alert('Your browser does not support geolocation'); 
    } 

</script> 
<body> 
    <div id="map_canvas"></div> 
</body> 
+0

当位置改变时不要重新创建地图,只需更新地图上标记的位置即可。 – geocodezip

回答

1

当位置发生变化时,不要重新创建地图,只需更新地图上标记的位置即可。

var map, GeoMarker; 
function initialize() { 
      var mapOptions = { 
       zoom: 17, 
       center: new google.maps.LatLng(-34.397, 150.644), 
       mapTypeId: google.maps.MapTypeId.ROADMAP 
      }; 
      map = new google.maps.Map(document.getElementById('map_canvas'), 
      mapOptions); 
} 
setInterval (function() { 
    if (!GeoMarker) { 
     GeoMarker = new GeolocationMarker(); 
    } 
    GeoMarker.setCircleOptions({fillColor: '#808080'}); 

    google.maps.event.addListenerOnce(GeoMarker, 'position_changed',  function() { 
      map.setCenter(this.getPosition()); 
      map.fitBounds(this.getBounds()); 
    }); 

    google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) { 
     alert('There was an error obtaining your position. Message: ' + e.message); 
    }); 
    console.log('updating'); 
    GeoMarker.setMap(map); 
},10000); 
google.maps.event.addDomListener(window,'load',initialize); 

if(!navigator.geolocation) { 
    alert('Your browser does not support geolocation'); 
}