Google Maps API当前位置不断更新

时间:2018-10-04 11:45:37

标签: javascript google-maps

我正在将Google Maps API集成到应用程序中,并且Google Maps API需要我当前的位置。

我可以按预期提供我的当前位置,但是如何使用我的居住位置动态更新它呢?

这是我的代码:

@push('scripts')
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=&libraries=places&callback=initMap" async defer></script>
<script>
    // Loading in google maps
    function initMap() {
        let spain = {lat: 40.4637, lng: -3.7492};
        map = new google.maps.Map(document.getElementById('map'), {
            zoom: 16,
            center: spain
        });

        let infoWindow = new google.maps.InfoWindow;
        let markers = {!! $markers->toJson() !!};

        let hotspotLoc = {
            lat: Object.values(markers)[0].lat,
            lng: Object.values(markers)[0].lng
        };
        map.setCenter(hotspotLoc);

        // Loading in Markers from the database
        $.each(markers, function (key, marker) {
            let id = marker.id;
            let name = marker.name;
            let addres = marker.addres;
            let lesson = 0;
            if (marker.lesson && marker.lesson.length > 0) {
                lesson = marker.lesson[0].id;
            }

            let lat = marker.lat;
            let lng = marker.lng;
            let type = marker.type;

            let markerLatlng = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));

            let mark = new google.maps.Marker({
                position: markerLatlng,
                map: map,
                lesson: lesson,
            });


            new google.maps.event.trigger(markers, 'click');

            mark.setMap(map);
        });
    }

    function handleLocation(browserGeoLocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeoLocation ? 'Error: The Geolocation service has failed!' :
            'Error: Your browser doesn/t support Geolocations!');

        infoWindow.open(map);
    }

    function disableLesson() {
        const listOfLesson = $(".lockLesson:not(.disabled)").slice(1);
        listOfLesson.each(function() {
            $(this).addClass('disabled');
            //$(this).find('.d-flex .btn-dark').append('<div class="fas fa-lock fa-lg mx-2"></div>');
            $(this).find('.d-flex .d-none').removeClass("d-none");
        });
    }

    $(() => {
        disableLesson();
    });
</script>
<script async defer
        src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAtqWsq5Ai3GYv6dSa6311tZiYKlbYT4mw&callback=initMap">
</script>

@endpush

希望有人知道如何更新它,这样我就可以继续我的项目。

1 个答案:

答案 0 :(得分:0)

您必须使用setInterval javascript函数

            // call funtion to get and set location
            setInterval(function () {
                // Call function get and set location
            }, 5000);

参考:https://gist.github.com/pawel-dubiel/3714643/36d78efa85fa413fff79669423de5ec08c77e34c