Search code examples
javascriptgoogle-maps-api-3

Set Origin and waypoint realtime google maps api js


Can I set origin of directions realtime for example with setInterval. Also I want to set location of waypoint live by getting from db. I tried many ways, but I didn't find way since I have no big experience on google maps API. I tried setPosition() for marker but marker is moving not direction point. I inserted setDirections() into setInterval but it is not getting new response. I inserted this.directionsService.route into setInterval but it is not worked setInterval worked 1time and stopped and gave error. Please help me to do it.

route() {
    let carrier_location = $.ajax({
        type: "GET",
        url: '{{ route("get-carrier-location", $order->car_id) }}',
        async: false
    }).responseText;
    const me = this;

    this.directionsService.route({
            origin: '{{ $order->car->latitude }},{{ $order->car->longitude }}',
            waypoints: [{location: carrier_location}],
            destination: '{{ $order->customer_post->from_latitude }},{{ $order->customer_post->from_longitude }}',
            travelMode: this.travelMode,
        },
        (response, status) => {
            if (status === "OK") {
                me.directionsRenderer.setDirections(response);

                var leg = response.request;

                new google.maps.Marker({
                        position: new google.maps.LatLng(leg.origin.location.lat(),leg.origin.location.lng()),
                        map: me.map,
                        icon: {
                            url: '{{ asset('front/dist/images/red-flag.png') }}',
                        scaledSize: new google.maps.Size(35, 40), // scaled size
                        origin: new google.maps.Point(0, 0), // origin
                        anchor: new google.maps.Point(15, 15)
                    },
                    title: 'start'
            });

                new google.maps.Marker({
                    position: new google.maps.LatLng(leg.destination.location.lat(),leg.destination.location.lng()),
                    map: me.map,
                    icon: {
                        url: '{{ asset('front/dist/images/placeholder.png') }}',
                        scaledSize: new google.maps.Size(35, 35), // scaled size
                        origin: new google.maps.Point(0, 0), // origin
                        anchor: new google.maps.Point(16, 36)
                    },
                    title: 'end'
            });
                let marker_3 = new google.maps.Marker({
                        position: new google.maps.LatLng(leg.waypoints[0].location.location.lat(),leg.waypoints[0].location.location.lng()),
                        map: me.map,
                        icon: {
                            url: '{{ asset('front/dist/images/truck_icon.png') }}',
                        scaledSize: new google.maps.Size(35, 35), // scaled size
                        origin: new google.maps.Point(0, 0), // origin
                        anchor: new google.maps.Point(16, 36)

                    },
                    title: 'waypoint0'
            });
            } else {
                // malumot topilmasa error chiqarish
                // window.alert("Directions request failed due to " + status);
            }
        }
    );
}

Solution

  • If you want to update your location of the origin and direction marker, you need to update your origin and then recalculate the directions, using directionsService.route().

    function calculateAndDisplayRoute(directionsService, directionsRenderer) {
      let orgLat = 37.77;
      setInterval(() => {
        directionsService
          .route({
            origin: { lat: orgLat, lng: -122.447 },
            destination: { lat: 37.768, lng: -122.511 },
            travelMode: google.maps.TravelMode.DRIVING,
          })
          .then((response) => {
            directionsRenderer.setDirections(response);
            orgLat = orgLat - 0.001;
          })
          .catch((e) => window.alert("Directions request failed due to " + status));
      }, 2000);
    }
    

    I have created a jsfiddle that shows the map with a origin that moves every 2 sec, and updates the map with directions. exchange that for a callback from a database and the marker should change every time the callback fires.