Last Updated: September 30, 2022
·
1.898K
· karouani

JSTS Buffered Polyline in route Service (google maps V3)

Hello everyone, I do not know if someone has already lived the same thing as me, I work with JSTS API to create a polygon that surrounds the route of the google services but the problem is that when there are intersections in the polygon route Does not take the given distance but the complete surface between the two roads, the following image [image what i want and problem results] explains the problem in detail, and here is the code used.
Result and what whant
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script> <script src="http://marocexpress.marocgeo.ovh/modules/trip/js/javascript.util.js"></script> <script src="http://marocexpress.marocgeo.ovh/modules/trip/js/jsts.js"></script>

   <div id="map-canvas"></div>
  <div id="directions-panel"></div>

 <script type="text/javascript">
        var mapCanvas = "map-canvas";
    var map;
    var directionsService = new google.maps.DirectionsService;
    var directionsDisplay = new google.maps.DirectionsRenderer;
    var mapConfig = {
        zoom: 6,
        center: { lat: 32.082575, lng: -6.921387 },
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControlOptions: {
            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
            mapTypeIds: [google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN]
        },
        overviewMapControl: true,
        scaleControl: true,
        streetViewControl: true,
        panControl: true,
        rotateControl: true,
        maxZoomForCenter:17
    };

function initialize() {
    map = new google.maps.Map(document.getElementById(mapCanvas),mapConfig);
    directionsDisplay.setMap(map);
    calculateAndDisplayRoute(directionsService, directionsDisplay);
};

function calculateAndDisplayRoute(directionsService, directionsDisplay) {
    var waypts = [];
    var checkboxArray = document.getElementById('waypoints');

    waypts.push({
        location: new window.google.maps.LatLng(33.494873,-7.718875),
        stopover: true
    });

    waypts.push({
        location: new window.google.maps.LatLng(33.595501,-7.578152),
        stopover: true
    });


    directionsService.route({
      origin: new window.google.maps.LatLng(33.563656, -7.636282),
      destination: new window.google.maps.LatLng(33.477188, -7.945458),
      waypoints: waypts,
      optimizeWaypoints: true,
      travelMode: 'DRIVING'
    }, function(response, status) {
      if (status === 'OK') {
        directionsDisplay.setDirections(response);
        var route = response.routes[0];

        var legs = response.routes[0].legs;
        overviewPath = response.routes[0].overview_path,
        overviewPathGeo = [];
        for (var i = 0; i < legs.length; i++) {
          var steps = legs[i].steps;
          for (j = 0; j < steps.length; j++) {
             var nextSegment = steps[j].path;
             for (k = 0; k < nextSegment.length; k++) {
                 overviewPathGeo.push(
                   [nextSegment[k].lng(), nextSegment[k].lat()]
                 );
            }
          }
        }
        bermudaTriangle = new google.maps.Polygon({
              paths: createPolygon(overviewPathGeo),
              fillColor: '#ff0000',
        });
        bermudaTriangle.setMap(map);

        var summaryPanel = document.getElementById('directions-panel');
        summaryPanel.innerHTML = '';
        // For each route, display summary information.
        for (var i = 0; i < route.legs.length; i++) {
          var routeSegment = i + 1;
          summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment +
              '</b><br>';
          summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
          summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
          summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
        }
      } else {
        window.alert('Directions request failed due to ' + status);
      }
    });
  }

  createPolygon = function(overviewPath) {
    if(overviewPath && overviewPath.length>= 0){
        last_width_long = 7;
        var distance = last_width_long / 1000;  //en km.
        distance = (distance / 111.12);
        geoInput = {
            type: "LineString",
            coordinates: overviewPath
        };
        var geoReader = new jsts.io.GeoJSONReader(),
            geoWriter = new jsts.io.GeoJSONWriter();
        var geometry = geoReader.read(geoInput).buffer(distance);
        var polygon = geoWriter.write(geometry);
        polygon_route = polygon;

        var areaCoordinates = [];
        var polygonCoordinates = polygon.coordinates[0];
        for (i = 0; i < polygonCoordinates.length; i++) {
            var coordinate = polygonCoordinates[i];
            areaCoordinates.push(new google.maps.LatLng(coordinate[1], coordinate[0]));//set latitude a
        }
        return areaCoordinates;
    }else return false;
    };
   google.maps.event.addDomListener(window, 'load', initialize);
  </script>

</code>

10 Responses
Add your response

Hello,do you resolve problem about intersections?
I have same problem.

over 1 year ago ·

HI @rgonzalez_in, Unfortunately no, I have not found a solution, if not I will share it, I posted this problem in the group of JSTS, and they are aborted this topic without answer.

over 1 year ago ·

I think...
May be order the array is the key.
But is a idea.
The array from Directions to JSTS.

over 1 year ago ·

I think that's you are rigth , Because the probleme is occured juste when the path have the short polyline in the some place , that's why the intersect method fail to recognize the correct way.

over 1 year ago ·

Any result public in this plataform.

over 1 year ago ·

Do you try concat all arrays from:
var polygon = geoWriter.write(geometry);
????

over 1 year ago ·

Hello:
Join all arrays with this code:

var polygonCoordinates=[];
//console.log(polygonCoordinates);
for (var i=0; i<polygon.coordinates.length; ++i) {
var current = polygon.coordinates[i];
for (var j=0; j<current.length; ++j)
polygonCoordinates.push(current[j]);
}

Reggards.

over 1 year ago ·

@rgonzalez_in
Hi i'm sorry for the late response , because i have a lot off task to execute ,
your code ;
var polygonCoordinates=[];
//console.log(polygonCoordinates);
for (var i=0; i<polygon.coordinates.length; ++i) {
var current = polygon.coordinates[i];
for (var j=0; j<current.length; ++j)
polygonCoordinates.push(current[j]);
}
not working wal for another example, check it from : http://marocgeo.net/jsts.html

over 1 year ago ·

I know.

Is only the way to join all arrays from jsts.

The buffer and order the coords is the key.
Order ther coords not available now.

Up the buffer to >= 100

lastwidthlong = 125;

Reggards.

over 1 year ago ·

@rgonzalez_in
Please can you give me ur contact ,
After change lastwidthlong = 125;
the result is important but the mistake to check if a point is in road is important so i think it's not useful to increase the length to a large number, else delta error increases

over 1 year ago ·