DEV Community

Sahil kashyap
Sahil kashyap

Posted on

Turf.js to php

Problem: Turfjs works well for client-side but I wanted to use it in server-side
Recently I had to check if a point lies inside of the polygon.

I was using spatial data in mysql. Mysql provides way(ST_Contains and some other ways) to check if a point lies in a polygon. But unfortunately it was not scanning all the rows.

I found turf.js was able to do this properly:
Here's I have used this with mapbox:

var point = turf.point([lon, lat]);
const PointwithinFeatureCollection = (point) => {
    var ptsWithin, found = false;
    var zip = false;
    turf.featureEach(data, function (currentFeature, featureIndex) {

        var geom = turf.getType(currentFeature)
        console.log('geom', geom);
        if (geom == 'MultiPolygon') {

            let coordinates = turf.multiPolygon(currentFeature.geometry.coordinates);

            ptsWithin = turf.booleanPointInPolygon(point, coordinates);
            console.log("Found in Multipolygon: : ", ptsWithin);
            if (ptsWithin) {
                zip =;

        } else if (geom == 'Polygon') {
            let coordinates = turf.polygon(currentFeature.geometry.coordinates);
            found = turf.booleanPointInPolygon(point, coordinates);
            console.log('found', found);
            if (found) {
                zip =;
    if (zip === false) {
        return {
            "success": false,
            "message": "Not within zipcode boundary",
            "response_code": 403
    } else {
        return {
            "success": true,
            "data": zip,
            "message": zip + " Zipcode is allowed.",
            "response_code": 200



Here's what I did to convert this code in php:-

1)I manually wrote all the turf function I was using.

2) Extracted those methods from the js file and wrote them in seperate js file. eg: point ,getType,featureEach,multiPolygon,polygon,booleanPointInPolygon I found these function is turf/helper,turf/invariant,turf/meta

  1. I used "npm install -g javascript-to-php" and then this js2php myfile.js > myfile.php

Note:You will have to manually edit some generated code and If you try to convert whole turf index.js sometimes it generates error

Top comments (0)