The intersection of a route with a polygon using the example of the Moscow Ring Road

Open in CodeSandbox

It is often necessary to draw a route between specified points, and then analyze in what areas or cities the segments of this route fall on. In this example, prepared data is used for creating a polygon defining the MKAD. After the route is received, a check is performed for whether its segments fall within this polygon using the method searchInside.

You can use the GeoQueryResult object to set options or data for an entire group of geo objects at once. Here you can see how route segments that are inside or outside of the ring road use different colors.

<!DOCTYPE html>

<html>
    <head>
        <title>
            Examples. The intersection of a route with a polygon using the
            example of the Moscow Ring Road.
        </title>
        <meta
            http-equiv="Content-Type"
            content="text/html; charset=UTF-8"
        />
        <!--
        Set your own API-key. Testing key is not valid for other web-sites and services.
        Get your API-key on the Developer Dashboard: https://developer.tech.yandex.ru/keys/
    -->
        <script
            src="https://api-maps.yandex.ru/2.1/?lang=en_RU&amp;apikey=<your API-key>"
            type="text/javascript"
        ></script>
        <script
            type="text/javascript"
            src="https://yandex.st/jquery/2.2.3/jquery.js"
        ></script>
        <script
            src="route_inside_polygon.js"
            type="text/javascript"
        ></script>
        <style>
            body,
            html {
                font-family: Arial;
                font-size: 11pt;
                padding: 0;
                margin: 0;
                width: 100%;
                height: 100%;
            }
            p {
                padding: 10px;
            }
            #map {
                width: 100%;
                height: 80%;
            }
        </style>
    </head>
    <body>
        <p>
            The route inside the ring road is marked in red, and outside is
            blue
        </p>
        <div id="map"></div>
    </body>
</html>
ymaps.ready(init);

function init() {
    var myMap = new ymaps.Map(
            "map",
            {
                center: [55.73, 37.75],
                zoom: 9,
            },
            {
                searchControlProvider: "yandex#search",
            }
        ),
        moscowPolygon;

    function onPolygonLoad(json) {
        moscowPolygon = new ymaps.Polygon(json.coordinates);
        // If we do not want the outline to be visible, we set the appropriate option.
        moscowPolygon.options.set("visible", false);
        /**
         * To correctly carried out geometric operations on the projected polygon,
         * you must add it to the map.
         */
        myMap.geoObjects.add(moscowPolygon);

        ymaps
            .route([
                [55.654884, 37.527034],
                [55.767305, 37.9761],
            ])
            .then(function (res) {
                // Combining all the route segments in a selection.
                var pathsObjects = ymaps.geoQuery(res.getPaths()),
                    edges = [];

                // Iterating all the segments and dividing them into sections.
                pathsObjects.each(function (path) {
                    var coordinates = path.geometry.getCoordinates();
                    for (var i = 1, l = coordinates.length; i < l; i++) {
                        edges.push({
                            type: "LineString",
                            coordinates: [
                                coordinates[i],
                                coordinates[i - 1],
                            ],
                        });
                    }
                });

                /**
                 * Creating a new selection containing the following:
                 * - sections that define the route;
                 * - the start and end points;
                 * - intermediate points.
                 */
                var routeObjects = ymaps
                        .geoQuery(edges)
                        .add(res.getWayPoints())
                        .add(res.getViaPoints())
                        .setOptions("strokeWidth", 3)
                        .addToMap(myMap),
                    // Finding all the objects that fall inside the ring road.
                    objectsInMoscow =
                        routeObjects.searchInside(moscowPolygon),
                    // Finding the objects that intersect with the ring road.
                    boundaryObjects =
                        routeObjects.searchIntersect(moscowPolygon);
                // Using different colors for objects inside, outside and intersecting the ring road.
                boundaryObjects.setOptions({
                    strokeColor: "#06ff00",
                    preset: "islands#greenIcon",
                });
                objectsInMoscow.setOptions({
                    strokeColor: "#ff0005",
                    preset: "islands#redIcon",
                });
                /**
                 * Getting objects outside the Moscow ring road
                 * by subtracting the obtained samples from the source sample.
                 */
                routeObjects
                    .remove(objectsInMoscow)
                    .remove(boundaryObjects)
                    .setOptions({
                        strokeColor: "#0010ff",
                        preset: "islands#blueIcon",
                    });
            });
    }

    $.ajax({
        url: "moscow.json",
        dataType: "json",
        success: onPolygonLoad,
    });
}