Search code examples
javascriptturfjs

How to get the wkt of circle in mapbox


I tried to get the wkt of circle in the mapbox. but not sure how to get the geojson of circle in the mapbox. I thought I can use following sample btw the problem is geojson.

var bounds = turf.bbox(markers);

Please help me!


Solution

  • I made the function to draw the circle using geojson.

    var createGeoJSONCircle = function(center, radiusInKm, points) {
    if(!points) points = 64;
    
    var coords = {
        latitude: center[1],
        longitude: center[0]
    };
    
    var km = radiusInKm;
    
    var ret = [];
    var distanceX = km/(111.320*Math.cos(coords.latitude*Math.PI/180));
    var distanceY = km/110.574;
    
    var theta, x, y;
    for(var i=0; i<points; i++) {
        theta = (i/points)*(2*Math.PI);
        x = distanceX*Math.cos(theta);
        y = distanceY*Math.sin(theta);
    
        ret.push([coords.longitude+x, coords.latitude+y]);
    }
    ret.push(ret[0]);
    
    return {
        "type": "geojson",
        "data": {
            "type": "FeatureCollection",
            "features": [{
                "type": "Feature",
                "geometry": {
                    "type": "Polygon",
                    "coordinates": [ret]
                }
            }]
        }
    };
    };
    

    The important thing of above function is points variable.

    The usage of function.

    var c = createGeoJSONCircle([-93.6248586, 41.58527859], 50);
    map.addSource("polygon", createGeoJSONCircle([-93.6248586, 41.58527859], 50));
    var cc = map.addLayer({
        "id": "polygon",
        "type": "fill",
        "source": "polygon",
        "layout": {},
        "paint": {
            "fill-color": "blue",
            "fill-opacity": 0.6
        }
    });
    

    And can get the wkt using wellknown.

    wellknown.stringify(c.data.features[0].geometry)
    

    Maybe it works well.