当路线穿过 google 地图中的多边形时显示警报,多边形附近没有标记

Show alert when route crosses polygon in google maps, no markers near the polygon

希望你们一切都好。

我在 google 地图上创建路线时遇到一点问题:

我根据存储在数据库中的信息动态创建多边形,并且我希望在我创建的路线经过多边形时显示警报。

问题是多边形内部没有生成标记,因此没有显示警报,所以我想知道是否有解决方法。

这是我使用的代码:

<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&v=3.exp&signed_in=true"></script>
    <script>
        var posiciones;

        var rendererOptions = {
            draggable: true
        };
        var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
        var directionsService = new google.maps.DirectionsService();
        var map;
        var polys = new Array();
        var resultado;

        var routCoordinates;
        var respuesta;
        var myPolygons = [

        <asp:Repeater ID='rptMarkers' runat='server'>
        <ItemTemplate>
                    {
                        "name": '<%# Eval("carajo") %>',
                        "coordinates": [
                            '<%# Eval("poligono1") %>',
                            '<%# Eval("poligono2") %>',
                            '<%# Eval("poligono3") %>',
                            '<%# Eval("poligono4") %>'
                        ]
                    }
            </ItemTemplate>
            <SeparatorTemplate>
                ,
            </SeparatorTemplate>
            </asp:Repeater>
                    ];

                    function drawPolygon(poly, polyLabel) {
                        var options = {
                            paths: poly,
                            strokeColor: '#AA2143',
                            strokeOpacity: 1,
                            strokeWeight: 2,
                            fillColor: "#FF6600",
                            fillOpacity: 0.7,
                            polyTitle: polyLabel
                        };

                        newPoly = new google.maps.Polygon(options);
                        newPoly.setMap(map);
                        polys.push(newPoly);
                    }

                    function sendPolygonForDrawing() {
                        for (var i = 0; i < myPolygons.length; i++) {
                            poly = new Array();
                            var coord = myPolygons[i].coordinates;
                            var lng = coord.length;
                            for (var j = 0; j < lng; j++) {
                                var longit_Latid = coord[j].split(',');
                                poly.push(new google.maps.LatLng(parseFloat(longit_Latid[0]), parseFloat(longit_Latid[1])));
                            }

                            drawPolygon(poly, myPolygons[i].name);
                            poly.pop();
                        }
                    }

                    var trucka = new google.maps.LatLng(21.984797, -102.27668);

                    function initialize() {
                        var mapOptions = {
                            zoom: 12,
                            center: trucka
                        };

                        map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
                        directionsDisplay.setMap(map);
                        //directionsDisplay.setPanel(document.getElementById('directionsPanel'));
                        directionsDisplay.setPanel(document.getElementById('hola'));

                        google.maps.event.addListener(directionsDisplay, 'directions_changed', function () {
                            computeTotalDistance(directionsDisplay.getDirections());
                        });


                        calcRoute();
                    }

                    function fncRouteZoneIntersection(response) {
                        //var myRoute = response.routes[0].legs[1];
                        var myRoute = response.routes[0].overview_path;
                        var lngLatCordinates = new Array();
                        //    for (var i = 0; i < myRoute.steps.length; i++) {
                        for (var i = 0; i < myRoute.length; i++) {
                                var marker = new google.maps.Marker({
                                    map: map,
                          //                      position: myRoute.steps[i].start_point
                                    position: myRoute[i]
                                });

                            //        lngLatCordinates.push(myRoute.steps[i].start_point);
                            lngLatCordinates.push(myRoute[i]);
                        }
                        return lngLatCordinates;
                    }

                    function calcRoute() {
                        sendPolygonForDrawing();
                        var lat = document.getElementById('hdnLatitudOrigen').value;
                        var lon = document.getElementById('hdnLongitudOrigen').value;
                        var request = {
                            origin: new google.maps.LatLng(lat, lon),
                            destination: new google.maps.LatLng(document.getElementById('hdnLatitudDestino').value, document.getElementById('hdnLongitudDestino').value),
                            waypoints: [
                                    { location: new google.maps.LatLng(document.getElementById('hdnLatitudParada1').value, document.getElementById('hdnLongitudParada1').value) }
                                    /*{ location: new google.maps.LatLng(document.getElementById('hdnLatitudParada2').value, document.getElementById('hdnLongitudParada2').value) },
                                    { location: new google.maps.LatLng(document.getElementById('hdnLatitudParada3').value, document.getElementById('hdnLongitudParada3').value) },
                                    { location: new google.maps.LatLng(document.getElementById('hdnLatitudParada4').value, document.getElementById('hdnLongitudParada4').value) },
                                    { location: new google.maps.LatLng(document.getElementById('hdnLatitudParada5').value, document.getElementById('hdnLongitudParada5').value) }*/
                            ],
                            travelMode: google.maps.TravelMode.DRIVING,
                            provideRouteAlternatives: true,
                            avoidHighways: false,
                            avoidTolls: false
                        };
                        directionsService.route(request, function (response, status) {
                            if (status == google.maps.DirectionsStatus.OK) {
                                directionsDisplay.setDirections(response);

                                respuesta = response;
                                var routCoordinates = fncRouteZoneIntersection(response);//this function populates the routCoordinates with the JSON data of the route.
                                var exist = new Array();

                                for (var i = 0; i < polys.length; i++) {//polys holds all polygons objects.
                                    for (var j = 0; j < routCoordinates.length; j++){ 
                                        //                    if (google.maps.geometry.poly.containsLocation(new google.maps.LatLng(routCoordinates[j].k, routCoordinates[j].A), polys[i]) == true){
                                        if (google.maps.geometry.poly.containsLocation(routCoordinates[j], polys[i]) == true) {
                                            //alert('CARAJO!');
                                            alert(polys[i].polyTitle);
                                            exist.push(polys[i].polyTitle);
                                            break;
                                            /*this breaks the loop checking when a point is found inside a polygon 
                                        and go check the next one, because knowing that one point of the route is 
                                        inside a polygon is enough*/
                                        }
                                    }
                                }
                                google.maps.event.addListener(directionsDisplay, 'directions_changed', updateInfo);
                                updateInfo();
                            }
                        });
                    }

                    function calcularPaso(){
                         var tolo = fncRouteZoneIntersection(respuesta);
                         var existe = new Array();

                         for (var i = 0; i < polys.length; i++) {
                            for (var j = 0; j < tolo.length; j++) {
                             if (google.maps.geometry.poly.containsLocation(tolo[j], polys[i]) == true) {
                                //alert('simon');
                             }
                            }
                         }
                    }

                    function updateInfo() {
                        //alert('carajo')
                        posiciones = '';
                        var route = directionsDisplay.getDirections().routes[0];
                        // var routes = response.routes;
                        var points = route.overview_path;
                        var ul = document.getElementById("vertex");
                        var elems = ul.getElementsByTagName("li")
                        for (var i = 0; i < elems.length; i++) {
                            elems[i].parentNode.removeChild(elems[i]);
                        }
                        for (var i = 0; i < points.length; i++) {
                            var li = document.createElement('li');
                            li.innerHTML = getLiText(points[i]);
                            ul.appendChild(li);
                            posiciones = posiciones + getLiText(points[i]);
                        }
                        document.getElementById("txtResultado").value = posiciones;
                        //document.getElementById("hdnResultado").value = posiciones;
                        calcularPaso();
                    }

                    function getLiText(point) {
                        var lat = point.lat(),
                            lng = point.lng();
                        return "2 " + lng + "," + lat;
                        return lat + ",2 " + lng + ",";
                    }

                    function computeTotalDistance(result) {
                        var total = 0;
                        var myroute = result.routes[0];
                        for (var i = 0; i < myroute.legs.length; i++) {
                            total += myroute.legs[i].distance.value;
                        }
                        total = total / 1000.0;
                        document.getElementById('total').innerHTML = total + ' km';
                    }

                    google.maps.event.addDomListener(window, 'load', initialize);

<div id="map-canvas" style="width: 100%; height: 400px"></div>
<div id="hola">
    <label>Puntos</label>
    <ul id="vertex" runat="server"></ul>
</div>
<div id="directionsPanel" style="width: 30%; height: 600px;">
    <p>
        Total Distance: <span id="total"></span>

    </p>
</div>

在我发送的图片上,您可以看到黄色的多边形。

希望能帮到你。

谢谢!

您可以使用几何库中的[containsLocation(point:LatLng, polygon:Polygon)][1]方法。您可以使用它来查找给定点是否落在多边形内,将点和多边形传递给 google.maps.geometry.poly.containsLocation()。如果点在多边形内或其边缘,则函数 returns 为真。

https://developers.google.com/maps/documentation/javascript/geometry#containsLocation