首页 > 解决方案 > 如何通过单击 Google 地图上的 POI 标记直接将目的地(航点)添加到路线

问题描述

我正在实现一个与谷歌地图相关的功能——旅行计划,它可以让用户在谷歌地图上自定义他们自己的旅行路线。但是,我只是实现了允许用户通过向数据库提交纬度/经度来创建他们旅行的目的地(航点)的功能,然后在加载 TripDetailed 视图时在谷歌地图上显示这些航点数据。当我看到 road-tripper 网站时,它有一个非常酷的功能,可以让用户通过点击谷歌地图上的 POI 标记直接将目的地(航点)添加到路线中,即当用户点击特定的 POI 时,它会生成带有“添加到旅行”按钮的信息窗口。当用户单击该按钮时,所选 POI 将作为航路点添加到现有行程路线中,并且谷歌地图会更新行程路线。

这是我的旅行计划视图

我想单击此 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代码,点击地图时可以获取纬度/经度,但我不知道为什么它不能被推入航点[]数组:

                //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 中实现此功能的提示?非常感谢。

标签: javascriptc#google-maps

解决方案


好的,我解决了这个问题。只是使用 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>


推荐阅读