How to draw a polygon around a polyline in JavaScript?

前端 未结 2 1440
天命终不由人
天命终不由人 2020-11-28 12:43

I want to draw a polygon around a polyline. The polyline in my case is a Google Maps direction and I need to show a polygon around it within the Google Maps canvas.

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 13:28

    This is the working solution. You can find the JSTS files at coderwall.com.

    var overviewPath = response.routes[0].overview_path,
    overviewPathGeo = [];
    for (var i = 0; i < overviewPath.length; i++) {
       overviewPathGeo.push(
          [overviewPath[i].lng(), overviewPath[i].lat()]
       );
    }
    
    var distance = value / 10000, // Roughly 10km
    geoInput = {
    type: "LineString",
        coordinates: overviewPathGeo
    };
    var geoReader = new jsts.io.GeoJSONReader(),
        geoWriter = new jsts.io.GeoJSONWriter();
    var geometry = geoReader.read(geoInput).buffer(distance);
    var polygon = geoWriter.write(geometry);
    
    var oLanLng = [];
    var oCoordinates;
    oCoordinates = polygon.coordinates[0];
    for (i = 0; i < oCoordinates.length; i++) {
       var oItem;
       oItem = oCoordinates[i];
       oLanLng.push(new google.maps.LatLng(oItem[1], oItem[0]));
    }
    
    var polygone = new google.maps.Polygon({
        paths: oLanLng,
        map:map
    });
    

提交回复
热议问题