将用户位置与 java 脚本中的 google 地图同步

sync users location with google maps in java script

是否可以使用地理定位同步用户位置?这样,如果用户正在旅行,他的位置将在页面上更新,有些类似于导航他的位置...

我试过了,但是整个地图一直在刷新,加载需要时间...它工作正常,但是,有没有更好的方法可以让我跟踪用户的位置?

    <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>

当位置改变时不要重新创建地图,只更新标记在地图上的位置。

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');
}