Как добавить пункты назначения (путевые точки) в маршрут напрямую, нажав на маркер POI на Картах Google - PullRequest
0 голосов
/ 04 июля 2018

Я реализую функцию, относящуюся к карте Google - планы поездок, которая позволяет пользователю настраивать собственный маршрут поездки на карте Google. Тем не менее, я просто реализую функцию, которая позволяет пользователю создать пункт назначения (путевую точку) своей поездки, отправив значение lat / long в базу данных, а затем отобразить эти данные путевой точки на карте Google при загрузке представления TripDetailed. Когда я увидел веб-сайт Road-Tripper, у него была очень интересная функция, позволяющая пользователям добавлять пункты назначения (путевые точки) к маршруту напрямую, нажимая маркер POI на Картах Google, то есть когда пользователь щелкает конкретную POI, он генерирует информационное окно с кнопкой «Добавить в поездку». Когда пользователь нажимает эту кнопку, выбранный POI будет добавлен в качестве путевой точки в существующий маршрут поездки, и карта Google обновит маршрут поездки.

Это мой план поездки

Я хочу щелкнуть этот POI, чтобы установить его как одну из моих путевых точек на текущем маршруте

Вот мой код JS:

            //Calculate Destination and Display Route on the Google Maps
            function calculateDisplayRoute(directionsDisplay, directionsService) {
                var waypts = [];
                for (var i = 1; i < destinationcount - 1; i++) { //Get rid of the starting and ending point
                    waypts.push({
                        location: new google.maps.LatLng(Lats[i], Lngs[i]),
                        stopover: true
                    });
                }
                            
                google.maps.event.addListener(map, 'click', function (event) {                    
                //I WANT TO IMPLETEMENT WHEN USER CLICK A POI MARKER ON MAP, IT CAN BE PUSH INTO THE waypts[] array
                    waypts.push({
                        location: new google.maps.LatLng(event.latLng.lat(), event.latLng.lng()),
                        stopover: true
                    });                    
                    //alert(event.latLng.lat() + ", " + event.latLng.lng());
                });
            
                // Retrieve the start and end locations and create a DirectionsRequest using
                // DRIVING directions.
                directionsService.route({
                    origin: start,
                    destination: end,
                    waypoints: waypts, // Since we need to matching the order sequence with the list on the right, we do not need the optimized waypoints
                    travelMode: 'DRIVING'
                }, function (response, status) {
                    // Route the directions and pass the response to a function to create
                    // markers for each step.
                    if (status === 'OK') {
                        directionsDisplay.setDirections(response);
                        renderDirectionsPolylines(response);
                    } else {
                        if (status === 'ZERO_RESULTS') {
                            window.alert('Directions request failed due to No route could be found between the origin and destination.');
                            for (i = 0; i < destinationcount - 1; i++) {
                                var id = i + 1;
                                document.getElementById("distance." + id).innerHTML = " Unable to get the distance from the next destination of the current trip.";
                            }
                            document.getElementById("distance." + destinationcount).innerHTML = " This is the end of your trip.";
                            document.getElementById("totaldistance").innerHTML = " Unable to get the total distance of the current trip";
                        }
                        if (status === 'UNKNOWN_ERROR') {
                            window.alert('A directions request could not be processed due to a server error. The request may succeed if you try again.');
                        }
                        if (status === 'REQUEST_DENIED') {
                            window.alert('The webpage is not allowed to use the directions service.');
                        }
                        if (status === 'OVER_QUERY_LIMIT') {
                            window.alert('The webpage has gone over the requests limit in too short a period of time.');
                        }
                        if (status === 'NOT_FOUND') {
                            window.alert('At least one of the origin, destination, or waypoints could not be geocoded.');
                        }
                        if (status === 'MAX_WAYPOINTS_EXCEEDED') {
                            window.alert('Too many DirectionsWaypoints were provided in the DirectionsRequest. Up to 23 waypoints allowed in each request, plus the origin and destination.');
                        }
                        if (status === 'INVALID_REQUEST') {
                            window.alert('The DirectionsRequest provided was invalid.');
                        }

                    }
                });
            }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

Вот мой js-код для добавления нового пункта назначения (путевой точки) к текущему маршруту поездки, он может получить широту / долготу при нажатии на карту, но я не знаю, почему его нельзя вставить в массив waypoint []:

                //I WANT TO IMPLETEMENT WHEN USER CLICK A POI MARKER ON MAP, IT CAN BE PUSH INTO THE waypts[] array
                    waypts.push({
                        location: new google.maps.LatLng(event.latLng.lat(), event.latLng.lng()),
                        stopover: true
                    });                    
                    //alert(event.latLng.lat() + ", " + event.latLng.lng());
                });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Может кто-нибудь дать мне несколько советов о том, как я мог бы реализовать эту функцию в JavaScript? Большое спасибо.

1 Ответ

0 голосов
/ 05 июля 2018

Хорошо, я решил эту проблему. Просто используя ajax для отправки lat / lng на контроллер, но я думаю о том, как можно напрямую разбить ломаную линию, чтобы добавить путевые точки в любом порядке к текущему маршруту поездки, вместо добавления его в качестве последнего пункта назначения поездки.

Вот мой обновленный код JS

                google.maps.event.addListener(map, 'click', function (event) {
                    //Now we using ajax to pass the value from view to controller
                    $.ajax({
                        type: "POST",
                        dataType: "json",
                        url: "/Account/AddMapDestination",
                        data: {
                            lat: event.latLng.lat(),
                            lng: event.latLng.lng(),
                            currentTripUid: '@Model.tripUID.ToString()'
                        },
                        success: function (result) {
                            if (result.success) {
                                alert(result.responseText);
                                location.reload(); //We do refresh page here to let page redener Destination result Panes with new sequence id.
                            } else {
                                alert(result.responseText);
                                location.reload();
                            }
                        },
                        error: function (result) {
                            alert("Error, your trip destination order sequence has not been changed.");
                            location.reload();
                        }
                    });
                   // alert(event.latLng.lat() + ", " + event.latLng.lng());
                });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...