Irek
Irek

Reputation: 57

How to save a polygon to the database

I've a OpenLayers web application. I've a function which after drawing a polygon generates the wkt format.

function generateWkt() {
    var featureWkt, modifiedWkt;
    var unionFeatures = [];

    layer.getSource().forEachFeature(function(f) {
        var featureClone = f.clone();
        featureWkt = wkt.writeFeature(featureClone);

        if(featureWkt.match(/MULTIPOLYGON/g)) {
            modifiedWkt = (featureWkt.replace(/MULTIPOLYGON/g, '')).slice(1, -1);
        } else {
            modifiedWkt = (featureWkt.replace(/,/g, ', ')).replace(/POLYGON/g, '');
        }

        unionFeatures.push(modifiedWkt);
    });

    layer.getSource().getFeatures().length ? $('#wkt').text('MULTIPOLYGON(' + unionFeatures + ')') : $('#wkt').text('');
}

I'd like to send data wkt(unionFeatures) to the database (phpmyadmin) using a button and then after refreshing the page, use the second button to load data into the polygons and show them on the map.

How to modify this code and what to put in the php file?

$('#postJson').click(function(){

    $.post('post_receiver.php', { ??? }, function(data){

    $('#response').html(data);

    }).fail(function() {
     alert( "Posting failed." );

    });
    return false;

});

please help step by step

Upvotes: 1

Views: 1133

Answers (1)

Amir
Amir

Reputation: 76

To save data:

//javascript code
//Send the json object to php file to save to db

$.ajax({
    type: 'post',
    dataType: "json",
    data:JSON.stringify(unionFeatures),
    url: "http://localhost/post_receiver.php", 
    success: function (data) {              
        alert("data sent");                 
    }
});

In post_receiver.php

$data = json_decode(trim(file_get_contents('php://input')), true);

//Save the $data to db using your logic. You may have to separate 
//multiple geometries WKT and insert separately.            
//***Saving logic ****

To show the data back to map :

In getData.php

//Retrieve data as a string through SQL query from db tables.

Call button click function from javascript to display geometries on map

function showGeometriesOnMap(){
    $.ajax({
        type: 'get',
        dataType: "json",
        url: "http://localhost/getData.php", 
        success: function (data) {              
            var retrievedData = JSON.parse(data);   

            //Display on map logic here 
            //See https://openlayers.org/en/latest/examples/wkt.html to 
            //show on map from WKT 
        }
    });
}

Upvotes: 1

Related Questions